View
243
Download
0
Category
Preview:
Citation preview
Introduction to OOP with Java
Instructor: AbuKhleif, Mohammad Noor
Sep 2017
www.abukhleif.com
OOP – Part 2
Instructor: AbuKhleif, Mohammad Noor
Sep 2017
www.abukhleif.com
Lecture 08:
Instructor
• AbuKhleif, ‘Mohammad Noor’• Computer Engineer (JU 2012-2017)• Software Automation Engineer @ Atypon – John Wiley and
Sons Company - Jordan Branch
• Reach me at:• www.abukhleif.com• moh.noor94@gmail.com• facebook.com/moh.noor94• twitter.com/moh_noor94
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
3
Course
• Java SE Basics• Object Oriented Programming• Course Page:
www.abukhleif.com/courses/java-101-sep-2017• Or, go to: www.abukhleif.com Courses Java 101 Course
– Sep 2017• Course Facebook Group:
www.facebook.com/groups/AKF2017Java
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
4
Static Variables, Constants, and Methods
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
6
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);
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
8
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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
9
‘Welcome to Java’ Program - Revisit
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
10
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Example
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com 11
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++;
}
/** Return numberOfObjects */
static int getNumberOfObjects() {
return numberOfObjects;
}
/** Return the area of this circle */
double getArea() {
return radius * radius * PI;
}
}
Example
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com 12
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;
// 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 + ")");
}
}
Example
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com 13
UML Class Diagram: Static Members Example
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
14
Circle
radius: double
numberOfObjects: int
getNumberOfObjects(): int
getArea(): double
1 radius
circle1
radius = 1
numberOfObjects = 2
instantiate
instantiate
Memory
2
5 radius
numberOfObjects
circle2
radius = 5
numberOfObjects = 2
After two Circle
objects were created,
numberOfObjects
is 2.
• Static members are underlined in UML class diagrams.
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 staticmembers.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
16
Let’s Code
• Build a class that can count the number of instances of itself.
• Make 3 objects of this class and print thenumber of instances before and after eachone.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
17
Visibility Modifiers
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
18
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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
20
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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
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
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
22
‘Welcome to Java’ Program - Revisit
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
23
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Visibility Modifiers: Methods and Data Fields Example
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
24
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();
}
}
package p1; package p2;
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();
}
}
Visibility Modifiers: Classes Example
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
25
class C1 {
...
}
public class C2 {
can access C1
}
package p1; package p2;
public class C3 {
cannot access C1;
can access C2;
}
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).
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
26
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.
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).
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
27
UML Class Diagrams (2)
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
28
UML Class Diagrams
• The (-) sign indicates a private modifier.
• The (+) sign indicates a public modifier.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
29
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.
Data Field Encapsulation
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
30
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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
32
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)
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
33
IntelliJ IDEA Shortcuts
Alt + Insert
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
34
Example
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com 35
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
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com 36
/** 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
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com 37
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());
}
}
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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
38
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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
39
Homework
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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
41
Homework
Part 2:
Write a test application named UtilityTest that demonstrates class Utility capabilities.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
42
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, well-designed, and well-styled.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
43
- Eng. Asma Abdel Karim Computer Engineering Department, JU Slides.- Liang, Introduction to Java Programming 10/e
Instructor: AbuKhleif, Mohammad Noor
Sep 2017
www.abukhleif.com
References:
End of Lecture =D
Recommended