Object Oriented
Programming
with Java II
Dr. Mohamed K. Hussein
Lecture 5
Associate Prof., Computer Science department,
Faculty of Computers & Information Science,
Suez Canal University
Email: [email protected]
Lecture outcomes
• The protected Data and Methods
• Visibility Modifiers
• Preventing Extending and Overriding
• Polymorphism
• Dynamic Binding
• Casting Objects
• The instanceof Operator
• The Object’s equals Method
• The ArrayList Class
Dr. Mohamed K. Hussein 2
The protected Data and Methods
• A protected member of a class can be accessed from a subclass.
• private members can be accessed only from inside of the class,
• public members can be accessed from any other classes.
• protected allow subclasses to access data fields or methods defined in the
superclass,
• Do not to allow nonsubclasses to access these data fields and methods.
Visibility increases
private, none (if no modifier is used), protected, public
Dr. Mohamed K. Hussein 3
Visibility modifiers
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }
package p2;
public class C3 public class C4 public class C5 {
extends C1 { extends C1 { C1 o = new C1();
can access x; can access x; can access o.x;
can access y; can access y; cannot access o.y;
can access z; cannot access z; cannot access o.z;
cannot access u; cannot access u; cannot access o.u;
can invoke m(); can invoke m(); cannot invoke o.m();
} } }
Dr. Mohamed K. Hussein 4
Accessibility Summary
Modifier Accessed Accessed Accessed Accessed
on members from the from the from a from a different
in a class same class same package subclass package
public
protected -
default - -
private - - -
Dr. Mohamed K. Hussein 5
Preventing Extending and Overriding
• Neither a final class nor a final method can be extended.
• A final data field is a constant.
• The final modifier indicates that a class is final and cannot be a parent class.
• The Math class is a final class.
• The String, StringBuilder, and StringBuffer classes are also final classes.
public final class A {
// Data fields, constructors, and methods
Dr. Mohamed K. Hussein 6
Preventing Extending and Overriding
• A final method cannot be overridden by its subclasses.
• For example, the following method m is final and cannot be
overridden:
public class Test {
// Data fields, constructors, and methods
public final void m() {
// Do something
}
} Dr. Mohamed K. Hussein 7
Polymorphism
• Polymorphism means that a variable of a supertype can refer to a subtype object.
• The inheritance relationship enables a subclass to inherit features from its superclass with
additional new features.
• A subclass is a specialization of its superclass
• Every instance of a subclass is also an instance of its superclass, but not vice versa.
• For example, every student is a person object, but not every person object is a
student.
Dr. Mohamed K. Hussein 8
public class Person{
private int age;
public Person(){age = 0;}
public Person(int age){this.age = age;}
Example
public class MyClass {
public int getAge(){return age;}
/** Main method */
public void setAge(int age){this.age = age;}
public static void main(String[] args) {
public String toString(){
printData(new Student(5, 3.2));
return “Age = “ + age;
printData(new Person(10));
}
}
}
class Student extends Person{
private int gpa;
public Student(){ // Display object properties
Super(); public static void printData(Person object) {
gpa = 0; System.out.println(“Data:\n" + object.toString());
} }
Public Student(int age, int gpa){
}
Super(age);
this.gpa = gpa;
}
public string toSTring(){
return Super.toStrng() + “\n” + “gpa = “ + gpa;
} Dr. Mohamed K. Hussein 9
}
Dynamic Binding
• A method can be implemented in several classes along the inheritance chain.
• The JVM decides which method is invoked at runtime.
• A method can be defined in a superclass and overridden in its subclass.
• For example, the toString() method is defined in the Object class and overridden in Person.
• Consider the following code:
Object o = new Person();
System.out.println(o.toString()); Which toString() method is invoked by o?
Dr. Mohamed K. Hussein 10
Dynamic Binding
• There are two terms: declared type and actual type.
• A variable must be declared a type.
• The type that declares a variable is called the variable’s declared type.
• o’s declared type is Object.
• A variable of a reference type can hold a null value or a reference to an instance of the
declared type.
• The instance may be created using the constructor of the declared type or its subtype.
• The actual type of the variable is the actual class for the object referenced by the variable.
• Here o’s actual type is Person, because o references an object created using new Person().
• Which toString() method is invoked by o is determined by o’s actual type.
• This is known as dynamic binding. Dr. Mohamed K. Hussein 11
Casting Objects
• One object reference can be typecast into another object reference.
• This is called casting object.
• The statement m(new Person());
• Assigns the object new Student() to a parameter of the Object type.
• This statement is equivalent to Object o = new Person(); // Implicit casting m(o);
• The statement Object o = new Person(), known as implicit casting, is legal because
an instance of Person is an instance of Object.
Dr. Mohamed K. Hussein 12
Casting Objects
• Consider the following statement: Person b = o;
• In this case a compile error would occur.
• Why does the statement Object o = new Person() work but Person b = o doesn’t?
• The reason is that a Person object is always an instance of Object,
• but an Object is not necessarily an instance of Person.
• Even though you can see that o is really a Person object, the compiler is not clever enough to know
it.
• To tell the compiler that o is a Person object, use explicit casting.
• The syntax is similar to the one used for casting among primitive data types.
• Person b = (Person)o; // ExplicitDr.casting
Mohamed K. Hussein 13
instanceof
• For the casting to be successful, you must make sure that the object to be cast is an instance of the
subclass.
• If an object is not an instance of person, it cannot be cast into a variable of object.
• It is a good practice to ensure that the object is an instance of another object before attempting a
casting.
• This can be accomplished by using the instanceof operator.
Object myObject = new Person();
/** Perform casting if myObject is an instance of Circle */
if (myObject instanceof Person) {
System.out.println("The perso age is " + ((Person)myObject).getAge());
}
Dr. Mohamed K. Hussein 14
Example
public class CastingDemo {
public static void main(String[] args) {
// Create and initialize two objects
Object object1 = new Student(21, 3);
Object object2 = new Person(12);
// Display Person and Student
displayObject(object1);
displayObject(object2);
}
public static void displayObject(Object object) {
if (object instanceof Student) {
System.out.println("The Student age is " + ((Student)object).getAge() + "The Student gpa is " + ((Student)object).getGpa());
}
else if (object instanceof Person) {
System.out.println("The Person age is " + ((Person)object).getAge());
}
}
} Dr. Mohamed K. Hussein 15
The Object’s equals Method
• Like the toString() method, the equals(Object) method is another useful method
defined in the Object class
• This method tests whether two objects are equal.
• The syntax for invoking it is: object1.equals(object2);
Dr. Mohamed K. Hussein 16
The Object’s equals Method
• The default implementation of the equals method in the Object class is:
public boolean equals(Object obj) {
return (this == obj);
}
• This implementation checks whether two reference variables point to the same object
using the == operator.
• You should override this method in your custom class to test whether two distinct objects
have the same content.
• The equals method is overridden in many classes in the Java API,
• such as java.lang.String and java.util.Date, toDr.
compare whether the contents of two objects are equal.
Mohamed K. Hussein 17
The Object’s equals Method
• You can override the equals method in the Person class
• To compare whether two Person are equal based on their
age as follows:
public boolean equals(Object o) {
if (o instanceof Person)
return age == ((Person)o).age;
else
return false;
}
Dr. Mohamed K. Hussein 18
The ArrayList Class
• An ArrayList object can be used to store a list of objects.
• You can create an array to store objects. java.util.ArrayList<E>
• But, once the array is created, its size is +ArrayList() Creates an empty list.
fixed. +add(o: E) : void Appends a new element o at the end of this list.
Adds a new element o at the specified index in this list.
+add(index: int, o: E) : void
• Java provides the ArrayList Removes all the elements from this list.
+clear(): void
Returns true if this list contains the element o.
• The following statement creates an ArrayList +contains(o: Object): boolean
Returns the element from this list at the specified index.
and assigns its reference to variable cities. +get(index: int) : E
Returns the index of the first matching element in this
+indexOf(o: Object) : int
list.
• This ArrayList object can be used to store +isEmpty(): boolean
Returns true if this list contains no elements.
strings. +lastIndexOf(o: Object) : int
Returns the index of the last matching element in this
+remove(o: Object): boolean list.
• ArrayList<String> cities = new
+size(): int Removes the element o from this list.
ArrayList<String>();
+remove(index: int) : boolean Returns the number of elements in this list.
Dr. Mohamed K. Hussein 19
ArrayList Example
import java.util.ArrayList;
public class TestArrayList {
public static void main(String[] args) {
ArrayList<String> cityList = new ArrayList<String>(); // Create a list to store cities
cityList.add(“Cairo"); // Add some cities in the list
cityList.add(“Alexandria");
cityList.add(“Ismilia");
cityList.add("Mansoura");
System.out.println("List size? " + cityList.size());
System.out.println("Is Cairo in the list? " + cityList.contains(“Cairo"));
System.out.println("The location of Alexandria in the list? “ + cityList.indexOf(“Alexandria"));
System.out.println("Is the list empty? " + cityList.isEmpty()); // Print false
cityList.add(2, “Giza"); // Insert a new city at index 2
cityList.remove(“Cairo"); // Remove a city from the list
cityList.remove(1); // Remove a city at index 1
System.out.println(cityList.toString()); // Display the contents in the list
for (int i = cityList.size() - 1; i >= 0; i––) // Display the contents in the list in reverse order
System.out.print(cityList.get(i) + " ");
System.out.println();
}
}
Dr. Mohamed K. Hussein 20
Array List Example
import java.util.ArrayList;
public class TestArrayList {
public static void main(String[] args) {
ArrayList<Person> People = new ArrayList<Person>(); // Create a list to store Persons
People.add( new Person(18)); // Add some cities in the list
People.add( new Person(22));
System.out.println(People.toString()); // Display the contents in the list
for (int i = People.size() - 1; i >= 0; i––) // Display the contents in the list in reverse order
System.out.println( “The age of the person? " + People.get(i).getAge() );
People.clear();
}
} Dr. Mohamed K. Hussein 21
Assignment 5
• The Account class is defined to model a bank account. An account class has:
• Add a field name of the String type to store the name of the customer.
• Other attributes include account number, balance, annual interest rate, and date created,
• A no-arg constructor that creates a default account.
• A constructor that constructs an account with the specified name, id, and balance.
• Add a data field named transactions whose type is ArrayList that stores the transaction for the
accounts. Each transaction include.
• The date of this transaction.
• The type of the transaction, such as 'W' for withdrawal, 'D’ for deposit.
• The amount of the transaction.
• The new balance after this transaction.
• Construct a Transaction with the specified date, type, balance, and description.
• Methods to deposit and withdraw funds that adds the transaction to the arrayList.
• Create two subclasses for checking and saving accounts.
• A checking account has an overdraft limit, but a savings account cannot be overdrawn.
Dr. Mohamed K. Hussein 22
Assignment 5
1. Draw the UML diagram for the classes and then implement them.
2. Write a test program that creates objects of Account, SavingsAccount, and CheckingAccount
and invokes their toString() methods.
3. Creates an Account with annual interest rate 1.5%, balance 1000, id 1122, and name Sarah .
4. Deposit $30, $40, and $50 to the account and withdraw $5, $4, and $2 from the account.
5. Print an account summary that shows account holder name, interest rate, balance, and all
transactions.
Dr. Mohamed K. Hussein 23
Thank you