0% found this document useful (0 votes)
21 views

Inheritance and Polymorphism

Uploaded by

jadjaffal01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Inheritance and Polymorphism

Uploaded by

jadjaffal01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Chapter 11 Inheritance and

Polymorphism

Dr. Asem Kitana


Dr. Abdallah Karakra

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
1
Inheritance
Suppose you will define classes to model circles,
rectangles, and triangles. These classes have many
common features. What is the best way to design
these classes so to avoid redundancy? The answer
is to use inheritance.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
2
Superclasses and Subclasses
 Inheritance enables you to define a general class
(i.e., a superclass) and later extend it to more
specialized classes (i.e., subclasses).
 The subclasses inherit the accessible properties
and methods from the superclass.
 A triangular arrow pointing to the superclass is
used to denote the inheritance relationship
between the classes involved.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
3
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
4
Superclasses and Subclasses
 A class defines a type. A type defined by a
subclass is called a subtype, and a type defined by
its superclass is called a supertype.
 Therefore, you can say that Circle is a subtype of
GeometricObject, and GeometricObject is a
supertype for Circle.
 The subclass and its superclass are said to form a
is-a relationship.

GeometricObject Circle Rectangle TestCircleRectangle

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
5
public class Person {
private String name; General
private int age; class
// constructor
public String getName() {return name;}
public void setName(String name){this.name=name;}

public int getAge() {return age;}


public void setAge(int age){this.age=age;}

}

public class Student extends Person { private int


studentNumber;
//constructor
public int getStudentNumber (){return studentNumber;}
public void setStudentNumber(int studentNumber)
{this.studentNumber = studentNumber;}

}
specific class
Liang, Introduction
Liang, to Java
Introduction Programming,
to Java Tenth
Programming andEdition, (c) 2013 Pearson
Data Structures, Education,
Twelfth Edition, (c) Inc.
2020All
rights reserved.
Pearson Education, Inc. All rights reserved.
public class Person {
private String name; General
private int age; class
// constructor
public String getName() {return name;}
public void setName(String name){this.name=name;}

public int getAge() {return age;}


public void setAge(int age){this.age=age;}

}
public class Employee extends Person {
private double salary; specific
private String departmentName; class
public double getSalary() {return salary;}

public void setSalary(double salary) {this.salary =salary;}

public String getDepartmentName() {return departmentName;}

public void setDepartmentName(String departmentName)


{this.departmentName
Liang, Introduction
Liang, Introduction to =
to Java
JavadepartmentName;}
Programming, Tenth
Programming andEdition, (c) 2013 Pearson
Data Structures, Education,
Twelfth Edition, (c) Inc.
2020All
} rights reserved.
Pearson Education, Inc. All rights reserved.
Are superclass’s Constructor
Inherited?
No. They are not inherited.
They are invoked explicitly or implicitly. Explicitly using
the super keyword.
A constructor is used to construct an instance of a class.
Unlike properties and methods, a superclass's
constructors are not inherited in the subclass. They can
only be invoked from the subclasses' constructors, using
the keyword super. If the keyword super is not explicitly
used, the superclass's no-arg constructor is
automatically invoked.
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
10
this(“No name yet”,0)

Liang, Introduction
Liang, to Java
Introduction Programming,
to Java Tenth
Programming andEdition, (c) 2013 Pearson
Data Structures, Education,
Twelfth Edition, (c) Inc.
2020All
rights reserved.
Pearson Education, Inc. All rights reserved.
Liang, Introduction
Liang, to Java
Introduction Programming,
to Java ProgrammingTenth
and Edition, (c) 2013 Twelfth
Data Structures, PearsonEdition,
Education, Inc. All
(c) 2020
rights reserved.
Pearson Education, Inc. All rights reserved.
7
Using the Keyword super
The keyword super refers to the superclass
of the class in which super appears. This
keyword can be used in two ways:
 To call a superclass constructor
 To call a superclass method

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
11
calling a superclass constructor
 The syntax to call a superclass’s constructor is:
super( ), or super(parameters)
 The statement super( ) invokes the no-arg
constructor of its superclass, and the statement
super(arguments) invokes the superclass
constructor that matches the arguments.
 The statement super( ) or super(arguments)
must be the first statement of the subclass’s
constructor.
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
12
Superclass’s Constructor Is Always
Invoked
A constructor may invoke an overloaded constructor or
its superclass’s constructor. If none of them is invoked
explicitly, the compiler puts super() as the first statement
in the constructor. For example,
public A() { public A() {
is equivalent to
} super();
}

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
} // some statements
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
11
CAUTION

You must use the keyword super to call the


superclass constructor. Invoking a
superclass constructor’s name in a subclass
causes a syntax error. Java requires that the
statement that uses the keyword super
appear first in the constructor.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
14
Constructor Chaining
Constructing an instance of a class invokes all the superclasses’ constructors
along the inheritance chain. This is known as constructor chaining.
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
} Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
15
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty(); 1. Start from the
} main method
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
16
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty(); 2. Invoke Faculty
} constructor
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
17
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
} 3. Invoke Employee’s no-
class Employee extends Person {
arg constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
18
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
4. Invoke Employee(String)
class Employee extends Person { constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
19
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
} 5. Invoke Person() constructor
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
20
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}
6. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
21
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}
7. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
22
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}
8. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
23
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
9. Execute println
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
24
Example on the Impact of a Superclass
without no-arg Constructor
Design Guide If
possible, you
Find out the errors in the program: should provide a
public class Apple extends Fruit { no-arg constructor
} for every class to
make the class
class Fruit { easy to extend and
public Fruit(String name) { to avoid errors
System.out.println("Fruit's constructor is invoked");
}
}

Since no constructor is explicitly defined in Apple, Apple’s default no-arg constructor is


defined implicitly. Since Apple is a subclass of Fruit, Apple’s default constructor automatically
invokes Fruit’s no-arg constructor. However, Fruit does not have a
no-arg constructor, because Fruit has an explicit constructor defined. Therefore, the
program cannot be compiled.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
24
Defining a Subclass
A subclass inherits from a superclass. You can also:
 Add new properties
 Add new methods
 Override the methods of the superclass

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
26
Overriding vs. Overloading

Overloading means to define multiple methods with the same name but
different signatures.

Overriding means to provide a new implementation for a method in the


subclass.

To override a method, the method must be defined in the subclass


using the same signature as in its superclass.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
28
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
28
Overriding vs. Overloading
 Overridden methods are in different classes related by
inheritance; overloaded methods can be either in the same
class, or in different classes related by inheritance.

 Overridden methods have the same signature; overloaded


methods have the same name but different parameter lists.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
29
Overriding
You can use a special Java syntax, called override annotation,
to place @Override before the overriding method in the
subclass. For example:

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
30
Calling Superclass Methods
You could rewrite the printCircle() method in the Circle class as
follows: (both are correct)

public void printCircle() {


System.out.println("The circle is created " +
getDateCreated() + " and the radius is " + radius);
}

public void printCircle() {


System.out.println("The circle is created " +
super.getDateCreated() + " and the radius is " + radius);
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
31
NOTE

An instance method can be overridden only


if it is accessible. Thus a private method
cannot be overridden, because it is not
accessible outside its own class. If a
method defined in a subclass is private in
its superclass, the two methods are
completely unrelated.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
30
NOTE

Like an instance method, a static method can


be inherited. However, a static method cannot
be overridden. If a static method defined in
the superclass is redefined in a subclass, the
method defined in the superclass is hidden.
The hidden static methods can be invoked using the
syntax SuperClassName.staticMethodName.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved. 31
Check Point
True or false? A subclass is a subset of a superclass.
False.
A subclass is an extension of a superclass and normally contains
more details information than its superclass.

What keyword do you use to define a subclass?


The extends keyword is used to define a subclass that extends a
superclass.

What is single inheritance? What is multiple inheritance? Does Java


support multiple inheritance?
Single inheritance allows a subclass to extend only one superclass.
Multiple inheritance allows a subclass to extend multiple classes.
Java does not allow multiple inheritance.
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
34
The Object Class and Its Methods
Every class in Java is descended from the
java.lang.Object class. If no inheritance is
specified when a class is defined, the
superclass of the class is Object.

public class Circle { public class Circle extends Object {


... Equivalent ...
} }

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
35
The toString() method in Object

The toString() method returns a string representation of the


object. The default implementation returns a string consisting
of a class name of which the object is an instance, the at sign
(@), and the object’s memory address in hexadecimal.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020 36
Pearson Education, Inc. All rights reserved.
The toString() method in Object
Loan loan = new Loan();
System.out.println(loan.toString());

The code displays something like


Loan@15037e5 . This message is not very
helpful or informative. Usually you should
override the toString method so that it returns a
digestible string representation of the object.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
37
toString

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
38
toString

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
39
Polymorphism
Polymorphism means that a variable of a supertype
can refer to a subtype object.

A class defines a type. A type defined by a


subclass is called a subtype, and a type defined by
its superclass is called a supertype. Therefore, you
can say that Circle is a subtype of
GeometricObject and GeometricObject is a
supertype for Circle.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020 39
Pearson Education, Inc. All rights reserved.
Polymorphism
Every instance of a subclass is also an
instance of its superclass, but not vice versa

For example, every circle is a geometric


object, but not every geometric object is a
circle. Therefore, you can always pass an
instance of a subclass to a parameter of its
superclass type.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
41
Polymorphism

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
42
Polymorphism

Which toString() method is invoked by o, the toString() method in


the Object class or the overridden toString() method in the
GeometricObject class ?

The toString( ) method in the GeometricObject class is invoked.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
43
Polymorphism

Hello, From C
Hello, From A
Hello, From B

Liang, Introduction
Liang, to to
Introduction Java Programming,
Java ProgrammingTenth
and E dition,
Data (c) 2013 Pearson
Structures, Education,
Twelfth Edition, Inc. All
(c) 2020
rights reser
Pearson Education, ved.
Inc. All rights reserved.
40
Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) {
Polymorphism allows methods to be used
m(new GraduateStudent()); generically for a wide range of object
m(new Student());
m(new Person()); arguments. This is known as generic
m(new Object());
}
programming. If a method’s parameter
type is a superclass (e.g., Object), you may
public static void m(Object x) {
System.out.println(x.toString()); pass an object to this method of any of the
}
}
parameter’s subclasses (e.g., Student or
String). When an object (e.g., a Student
class GraduateStudent extends Student {
} object or a String object) is used in the
class Student extends Person {
method, the particular implementation of
public String toString() { the method of the object that is invoked
return "Student";
} (e.g., toString) is determined dynamically.
}

class Person extends Object {


public String toString() {
return "Person";
}
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
44
Casting Objects
You have already used the casting operator to convert variables of
one primitive type to another. Casting can also be used to convert an
object of one class type to another within an inheritance hierarchy. In
the preceding section, the statement
m(new Student( ));

assigns the object new Student( ) to a parameter of the Object type.


This statement is equivalent to:

Object o = new Student( ); // Implicit casting


m(o);

The statement Object o = new Student(), known as implicit casting, is legal


because an instance of Student is automatically an instance of Object.
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
45
Why Casting Is Necessary?
Suppose you want to assign the object reference o to a variable of the
Student type using the following statement:

Student b = o;

A compile error would occur. Why does the statement Object o =


new Student() work and the statement Student b = o doesn’t? This is
because a Student object is always an instance of Object, but an
Object is not necessarily an instance of Student. Even though you can
see that o is really a Student object, the compiler is not so clever to
know it. To tell the compiler that o is a Student object, use an explicit
casting. The syntax is similar to the one used for casting among
primitive data types. Enclose the target object type in parentheses and
place it before the object to be cast, as follows:

Student b = (Student)o; // Explicit casting


Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
46
The instanceof Operator
Use the instanceof operator to test whether an object is an
instance of a class:

Object myObject = new Circle();


... // Some lines of code
/** Perform casting if myObject is an instance of
Circle */
if (myObject instanceof Circle) {
System.out.println("The circle diameter is " +
((Circle)myObject).getDiameter());
...
}

Use parentheses to ensure that casting is done before the . operator, as in


((Circle)myObject).getDiameter( );

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
48
true true false true true
Liang, Introduction
Liang, to Java
Introduction Programming,
to Java Tenth
Programming andEdition, (c) 2013 Pearson
Data Structures, Education,
Twelfth Edition, (c) Inc.
2020All
rights reserved.
Pearson Education, Inc. All rights reserved.
49
TIP
To help understand casting, you may also
consider the analogy of fruit, apple, and
orange with the Fruit class as the superclass
for Apple and Orange. An apple is a fruit, so
you can always safely assign an instance of
Apple to a variable for Fruit. However, a
fruit is not necessarily an apple, so you have
to use explicit casting to assign an instance
of Fruit to a variable of Apple.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
50
Casting

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
51
The equals Method
The equals() method compares the
contents of two objects. The default implementation of the
equals method in the Object class is as follows: This
implementation
public boolean equals(Object obj) { checks whether
return this == obj; two reference
} variables point to
the same object
using
the == operator

public boolean equals(Object o) { if (o


For example, the equals instanceof Circle) {
method is overridden in return radius == ((Circle)o).radius;
}
the Circle class. else
return false;
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
52
NOTE
The == comparison operator is used for
comparing two primitive data type values or for
determining whether two objects have the same
references. The equals method is intended to
test whether two objects have the same
contents, provided that the method is modified
in the defining class of the objects. The ==
operator is stronger than the equals method, in
that the == operator checks whether the two
reference variables refer to the same object.
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
53
Example: equals

false
true
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
54
The ArrayList Class
You can create an array to store objects. But the array’s size is fixed
once the array is created. Java provides the ArrayList class that can
be used to store an unlimited number of objects.
java.util.ArrayList<E>
+ArrayList() Creates an empty list.
+add(o: E) : void Appends a new element o at the end of this list.
+add(index: int, o: E) : void Adds a new element o at the specified index in this list.
+clear(): void Removes all the elements from this list. Returns true if
An ArrayList +contains(o: Object): boolean this list contains the element o.

object can +get(index: int) : E Returns the element from this list at the specified index.
+indexOf(o: Object) : int
be used to +isEmpty(): boolean
Returns the index of the first matching element in this list.
Returns true if this list contains no elements.
store a list +lastIndexOf(o: Object) : int Returns the index of the last matching element in this list.

of objects. +remove(o: Object): boolean


+size(): int
Removes the element o from this list.
Returns the number of elements in this list. Removes the
+remove(index: int) : boolean element at the specified index. Sets the element at the
+set(index: int, o: E) : E specified index.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
55
The ArrayList Class

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
56
Generic Type
ArrayList is known as a generic class with a generic
type E. You can specify a concrete type to replace E
when creating an ArrayList. For example, the
following statement creates an ArrayList and assigns
its reference to variable cities. This ArrayList object
can be used to store strings.
ArrayList<String> cities = new ArrayList<String>();

ArrayList<String> cities = new ArrayList<>();

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
56
ArrayList

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
58
Differences and Similarities between Arrays and
ArrayList

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
59
Example

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
58
Check Point
Suppose you want to create an ArrayList for storing integers. Can you
use the following code to create a list?
ArrayList<int> list = new ArrayList<int>();

No. This will not work because the elements stored in an ArrayList
must be of an object type. You cannot use a primitive data type such
as int to replace a generic type. However, you can create an ArrayList
for storing Integer objects as follows:
ArrayList<Integer> list = new ArrayList<Integer>();

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
59
System.out.print("The distinct integers are: ");

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
60
Array Lists from/to Arrays
Creating an ArrayList from an array of objects:
String[] array = {"red", "green", "blue"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(array));

Creating an array of objects from an ArrayList:


String[] array1 = new String[list.size()];

list.toArray(array1);

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
62
max and min in an Array List
String[] array = {"red", "green", "blue"};
System.out.pritnln(java.util.Collections.max( new
ArrayList<String>(Arrays.asList(array)));

String[] array = {"red", "green", "blue"};


System.out.pritnln(java.util.Collections.min(
new ArrayList<String>(Arrays.asList(array)));

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
63
Sort method

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
65
Shuffling an Array List
Integer[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5};
ArrayList<Integer> list = new
ArrayList<>(Arrays.asList(array));
java.util.Collections.shuffle(list);
System.out.println(list);

[95, 4, 5, 6, 34, 3, 5, 15, 3]

[6, 5, 5, 4, 3, 15, 3, 34, 95]

[6, 3, 4, 95, 15, 3, 5, 34, 5]

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
64
The protected Modifier
The protected modifier can be applied on
data and methods in a class. A protected data or a
protected method in a public class can be accessed
by any class in the same package or its subclasses,
even if the subclasses are in a different package.
private, default, protected, public
Visibility increases

private, none (if no modifier is used), protected, public

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
67
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 - - -

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
68
Visibility Modifiers
package p1;
public class C1 { public class C2 {
public int x; protected C1 o = new C1();
int y; int z; can access o.x; can
private int u; access o.y; can access
o.z; cannot access
protected void m() { o.u;
}
} 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; cannot
can access y; can access y; access o.y; cannot
can access z; cannot access z; access o.z; cannot
cannot access u; cannot access u; access o.u;
can invoke m(); can invoke m(); cannot invoke o.m();
} } }

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
69
A Subclass Cannot Weaken the Accessibility

A subclass may override a protected


method in its superclass and change its
visibility to public. However, a subclass
cannot weaken the accessibility of a
method defined in the superclass. For
example, if a method is defined as public in
the superclass, it must be defined as public
in the subclass.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
70
NOTE
The modifiers are used on classes and
class members (data and methods), except
that the final modifier can also be used on
local variables in a method. A final local
variable is a constant inside a method.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
71
The final Modifier
The final class cannot be extended:
final class Math {
...
}

The final variable is a constant:


final static double PI = 3.14159;

The final method cannot be


overridden by its subclasses.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
72
Check Point
How do you prevent a class from being
extended? How do you prevent a method from
being overridden?
Use the final keyword.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
73
Check Point
Indicate true or false for the following statements:
a.A protected data field or method can be accessed by any class in the same package.
b.A protected data field or method can be accessed by any class in different packages.
c.A protected data field or method can be accessed by its subclasses in any package.
d.A final class can have instances.
e.A final class can be extended.
f.A final method can be overridden.
g.True.
h.False. (But yes in a subclass that extends the class where the protected
data field is defined.)
i.True.
j.Answer: True
k.Answer: False
l.Answer: False
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
74
Review of concepts

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
75
Inheritance
Allow us to specify relationships between
types
–Abstraction, generalization, specification
–The “is-a” relationship
–Examples?

Why is this useful in programming?


–Next slide

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
Why useful: Code Reuse
General functionality can be written once and
applied to *any* subclass

Subclasses can specialize by adding members


and methods, or overriding functions

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
Inheritance Basics
 Inheritance allows programmer to define a
general class (superclass)
 Later you define a more specific class (subclass)
– Adds new details to general definition
 New class inherits all properties of initial,
general class

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
Superclasses and Subclasses
GeometricObject
-color: String The color of the object (default: white).
-filled: boolean Indicates whether the object is filled with a color (default: false).
-dateCreated: java.util.Date The date when the object was created.
+GeometricObject() Creates a GeometricObject.
+GeometricObject(color: String, filled: Creates a GeometricObject with the specified color and filled
boolean) values.
+getColor(): String Returns the color. Sets a new color.
+setColor(color: String): void Returns the filled property.
+isFilled(): boolean Sets a new filled property. Returns the dateCreated.
+setFilled(filled: boolean): void Returns a string representation of this object.
+getDateCreated(): java.util.Date
+toString(): String

Circle Rectangle
-radius: double -width: double

+Circle()
-height: double The setColor and setFilled methods to
+Circle(radius: double)
+Circle(radius: double, color: String,
+Rectangle()
+Rectangle(width: double, height: double)
set the color and filled properties.
filled: boolean)
+getRadius(): double
+Rectangle(width: double, height: double
color: String, filled: boolean)
These two public methods are defined
+setRadius(radius: double): void +getWidth(): double in the base class GeometricObject and
are inherited in Circle and Rectangle,
+getArea(): double +setWidth(width: double): void
+getPerimeter(): double +getHeight(): double
+getDiameter(): double
+printCircle(): void
+setHeight(height: double): void
+getArea(): double
so they can be used in the derived
+getPerimeter(): double class.
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, (c) 2020
Pearson Education, Inc. All rights reserved.
80

You might also like