Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 08: OOP Part 2 Instructor: AbuKhleif, Mohammad Noor Sep 2017 AbuKhleiF - 1
Instructor AbuKhleif, Mohammad Noor Computer Engineer (JU 2012-2017) Software Automation Engineer @ Atypon John Wiley and Sons Company - Jordan Branch Reach me at: moh.noor94@gmail.com facebook.com/moh.noor94 twitter.com/moh_noor94 3 Course Java SE Basics Object Oriented Programming Course Page: /courses/java-101-sep-2017 Or, go to: Courses Java 101 Course Sep 2017 Course Facebook Group: www.facebook.com/groups/akf2017java 4 AbuKhleiF - 2
Static Variables, Constants, and Methods 5 Static Variables, Constants, and Methods All variables declared in the data fields of the previous examples are called instance variables. An instance variable is tied to a specific instance of the class. It is not shared among objects of the same class. It has independent memory storage for each instance. 6 AbuKhleiF - 3
Static Variables, Constants, and Methods In the following example, the radius of the first object circle1 is independent of the radius of the second object circle2 : Circle circle1 = new Circle(); Circle circle2 = new Circle(5); 7 Static Variables, Constants, and Methods Static variables, also known as class variables, store values for the variables in a common memory location. A static variable is used when it is wanted that all instances of the class to share data. If one instance of the class changes the value of a static variables, all instances of the same class are affected. Static methods can be called without creating an instance of the class. 8 AbuKhleiF - 4
Static Variables, Constants, and Methods To declare a static variable or define a static method, put the modifier static in the variable or method declaration. Since constants in a class are shared by all objects of the class, they should be declared static. final static double PI = 3.14159265358979323846; Static variables and methods can be accessed from a reference variable or from their class name. 9 Welcome to Java Program - Revisit // This program prints Welcome to Java! public class Welcome { public static void main(string[] args) { System.out.println("Welcome to Java!"); 10 AbuKhleiF - 5
public class CircleWithStaticMembers { /** The radius of the circle */ double radius; final static double PI = 3.14159265358979323846; /** The number of the objects created */ static int numberofobjects = 0; /** Construct a circle with radius 1 */ CircleWithStaticMembers() { radius = 1.0; numberofobjects++; /** Construct a circle with a specified radius */ CircleWithStaticMembers(double newradius) { radius = newradius; numberofobjects++; Example /** Return numberofobjects */ static int getnumberofobjects() { return numberofobjects; /** Return the area of this circle */ double getarea() { return radius * radius * PI; 11 public class TestCircleWithStaticMembers { /** Main method */ public static void main(string[] args) { System.out.println("Before creating objects"); System.out.println("The number of Circle objects is " + CircleWithStaticMembers.numberOfObjects); // Create c1 CircleWithStaticMembers c1 = new CircleWithStaticMembers(); // Display c1 BEFORE c2 is created System.out.println("\nAfter creating c1"); System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" + c1.numberofobjects + ")"); // Create c2 CircleWithStaticMembers c2 = new CircleWithStaticMembers(5); // Modify c1 c1.radius = 9; Example // Display c1 and c2 AFTER c2 was created System.out.println("\nAfter creating c2 and modifying c1"); System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" + c1.numberofobjects + ")"); System.out.println("c2: radius (" + c2.radius + ") and number of Circle objects (" + c2.numberofobjects + ")"); 12 AbuKhleiF - 6
Example 13 UML Class Diagram: Static Members Example Circle radius: double numberofobjects: int getnumberofobjects(): int getarea(): double instantiate instantiate circle1 radius = 1 numberofobjects = 2 circle2 radius = 5 numberofobjects = 2 Memory 1 radius 2 5 radius numberofobjects After two Circle objects were created, numberofobjects is 2. Static members are underlined in UML class diagrams. 14 AbuKhleiF - 7
Relationship between Static and Instance Members An instance method can invoke and access static and instance members. A static method can only invoke and access static members. 15 Instance or Static? How to decide whether a variable or method should be an instance one or a static one? A variable or method that is dependent on a specific instance of the class should be an instance variable or method. Example: radius and getarea of the Circle class; each circle has its own radius and area. A variable or method that is not dependent on a specific instance of the class should be a static variable or method. Example: numberofobjects of the Circle class; all circles should share this value. 16 AbuKhleiF - 8
Let s Code Build a class that can count the number of instances of itself. Make 3 objects of this class and print the number of instances before and after each one. 17 Visibility Modifiers 18 AbuKhleiF - 9
Visibility Modifiers Visibility modifiers can be used to specify the visibility of a class and its members. A visibility modifier specifies how data fields and methods in a class can be accessed from outside the class. There is no restriction on accessing data fields and methods from inside the class. 19 Visibility Modifiers If no visibility modifier is used, then by default the classes, methods, and data fields are accessible by any class in the same package. This is known as package-private or package-access. 20 AbuKhleiF - 10
Packages Packages are used to organize classes. To do so, you need to add the following statement as the first statement in the program: package packagename; If a class is defined without the package statement, it is said to be placed in the default package. 21 Visibility Modifiers The public modifier can be used for classes, methods and data fields to denote that they can be accessed from any other classes. The private modifier makes methods and data fields accessible only from within its own class 22 AbuKhleiF - 11
Welcome to Java Program - Revisit // This program prints Welcome to Java! public class Welcome { public static void main(string[] args) { System.out.println("Welcome to Java!"); 23 Visibility Modifiers: Methods and Data Fields Example package p1; package p2; public class C1 { public int x; int y; private int z; public void m1() { void m2() { private void m3() { public class C2 { void amethod() { C1 o = new C1(); can access o.x; can access o.y; cannot access o.z; can invoke o.m1(); can invoke o.m2(); cannot invoke o.m3(); public class C3 { void amethod() { C1 o = new C1(); can access o.x; cannot access o.y; cannot access o.z; can invoke o.m1(); cannot invoke o.m2(); cannot invoke o.m3(); 24 AbuKhleiF - 12
Visibility Modifiers: Classes Example package p1; package p2; class C1 {... public class C2 { can access C1 public class C3 { cannot access C1; can access C2; 25 Visibility Modifiers: Note An object cannot access its private members, as shown in (b). It is OK, however, if the object is declared in its own class, as shown in (a). public class F { private boolean x; public static void main(string[] args) { F f = new F (); System.out.println(f.x); System.out.println(f.convert()); private int convert(boolean b) { return x? 1 : -1; (a) This is OK because object f is used inside the F class public class Test { public static void main(string[] args) { Foo f = new F(); System.out.println(f.x); System.out.println(f.convert(f.x)); (b) This is wrong because x and convert are private in F. 26 AbuKhleiF - 13
Visibility Modifiers: Conclusion The private modifier restricts access to within a class. The default modifier restricts access to within a package. The public modifier enables unrestricted access. The protected modifier (later). 27 UML Class Diagrams (2) 28 AbuKhleiF - 14
UML Class Diagrams Circle -radius: double -numberofobjects: int +Circle() +Circle(radius: double) +getradius(): double +setradius(radius: double): void +getnumberofobject(): int +getarea(): double The radius of this circle (default: 1.0). The number of circle objects created. Constructs a default circle object. Constructs a circle object with the specified radius. Returns the radius of this circle. Sets a new radius for this circle. Returns the number of circle objects created. Returns the area of this circle. The (-) sign indicates a private modifier. The (+) sign indicates a public modifier. 29 Data Field Encapsulation 30 AbuKhleiF - 15
Data Field Encapsulation It is not a good practice to allow data fields to be directly modified. Data may be tampered with. The class becomes difficult to maintain and vulnerable to bugs. To prevent direct modifications of data fields, you should declare the data fields private. This is known as data field encapsulation. 31 Data Field Encapsulation A private data field cannot be accessed by an object from outside the class that defines the private field. However, a client often needs to retrieve and modify a data field. To make a private data field accessible: Provide a get method to return its value. Provide a set method set a new value to it. 32 AbuKhleiF - 16
Data Field Encapsulation A get method has the following signature: public returntype getpropertyname() If the returntype is boolean, the get method is defined as follows by convention: public boolean isproperyname() A set method has the following signature: public void setpropertyname(datatype propertyvalue) 33 IntelliJ IDEA Shortcuts Alt + Insert 34 AbuKhleiF - 17
public class CircleWithPrivateDataFields { /** The radius of the circle */ private double radius = 1; /** The number of the objects created */ private static int numberofobjects = 0; /** Construct a circle with radius 1 */ public CircleWithPrivateDataFields() { numberofobjects++; /** Construct a circle with a specified radius */ public CircleWithPrivateDataFields(double newradius) { radius = newradius; numberofobjects++; Example 35 /** Return radius */ public double getradius() { return radius; /** Set a new radius */ public void setradius(double newradius) { radius = (newradius >= 0)? newradius : 0; /** Return numberofobjects */ public static int getnumberofobjects() { return numberofobjects; /** Return the area of this circle */ public double getarea() { return radius * radius * Math.PI; These two methods are the only way to access the radius. This method is the only way to read the numberofobjects. numberofobjectsis only modified when a new object is created, there is no other way to modify it. Example 36 AbuKhleiF - 18
public class TestCircleWithPrivateDataFields { /** Main method */ public static void main(string[] args) { // Create a Circle with radius 5.0 CircleWithPrivateDataFields mycircle = new CircleWithPrivateDataFields(5.0); System.out.println("The area of the circle of radius " + mycircle.getradius() + " is " + mycircle.getarea()); // Increase mycircle's radius by 10% mycircle.setradius(mycircle.getradius() * 1.1); System.out.println("The area of the circle of radius " + mycircle.getradius() + " is " + mycircle.getarea()); Example 37 Let s Code Create a class called Date that includes three pieces of information as instance variables: A month (int), a day (int) and a year (int). Your class should have a constructor that initializes the three instance variables and assumes that the values provided are correct. Provide a set and a get method for each instance variable. Provide a method displaydate that displays the month, day and year separated by forward slashes (/). Write a test application named DateTest that demonstrates classdate s capabilities. 38 AbuKhleiF - 19
Let s Code Create a class called Employee that includes three pieces of information as instance variables: A first name (String), a last name (String) and a monthly salary (double). Your class should have a constructor that initializes the three instance variables. If the monthly salary is not positive, set it to 0.0. Provide a set and a get method for each instance variable. Write a test application named EmployeeTest that demonstrates class Employee s capabilities. Create two Employee objects and display each object s yearly salary. Then give each Employee a 10% raise and display each Employee s yearly salary again. 39 Homework AbuKhleiF - 20
Homework Part 1: Build a class called Utility that has methods to analyze a String parameter: One method can get you the number of occurrences of the and a in a String, Another one that finds if a String is a Palindrome, Another one that finds if a number is Armstrong. 41 Homework Part 2: Write a test application named UtilityTest that demonstrates class Utility capabilities. 42 AbuKhleiF - 21
Homework Submission Submit only the Utility.java file. Upload your file to the Facebook group. Submission due: Thursday, Sep 28-08:00 PM Late submission will not be reviewed by the instructor. Public solutions upload goal is to share knowledge, you can see other s solutions, but, please, don t cheat yourself! Don t forget, your solution should be well-documented, welldesigned, and well-styled. 43 References: - Eng. Asma Abdel Karim Computer Engineering Department, JU Slides. - Liang, Introduction to Java Programming 10/e Instructor: AbuKhleif, Mohammad Noor Sep 2017 End of Lecture =D AbuKhleiF - 22