Download Chapter 9: Objects and Classes

Document related concepts
no text concepts found
Transcript
Chapter 11 Inheritance and
Polymorphism
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
1
Objectives












To define a subclass from a superclass through inheritance (§11.2).
To invoke the superclass’s constructors and methods using the super keyword
(§11.3).
To override instance methods in the subclass (§11.4).
To distinguish differences between overriding and overloading (§11.5).
To explore the toString() method in the Object class (§11.6).
To discover polymorphism and dynamic binding (§§11.7–11.8).
To describe casting and explain why explicit downcasting is necessary (§11.9).
To explore the equals method in the Object class (§11.10).
To store, retrieve, and manipulate objects in an ArrayList (§11.11).
To implement a Stack class using ArrayList (§11.12).
To enable data and methods in a superclass accessible from subclasses using the
protected visibility modifier (§11.13).
To prevent class extending and method overriding using the final modifier
(§11.14).
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
2
4 Fundamental Principles of OOP
 1.
Inheritance
– Inherit members from parent class
 2.
Abstraction
– Define and execute abstract actions
 3.
Encapsulation
– Hide the internals of a class
 4.
Polymorphism
 Access a class through its parent interface
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
3
1. Inheritance
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Types of Inheritance
 Inheritance
terminology
derived class
inherits
base class /
parent class
class
implements
interface
derived interface
implements
base interface
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
5
Inheritance
Inheritance Objects can relate to each other
with either a “has a, parent”, “uses, child of parent” or
an “is a” relationship. “Is a, parent it self” is the
inheritance way of object relationship.
 Like., family tree.
 This LibraryAsset is a superclass, or base class, that
maintains only the data and methods that are common to
all loanable assets.
Book, magazine, audiocassette and microfilm will all be
subclasses or derived classes or the LibraryAsset class, and
so they inherit these characteristics. The inheritance
relationship is called the “is a” relationship. A book “is a”
LibraryAsset, as are the other 3 assets.
6

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Get
Return _checkedOut
End Get
Set(ByVal Value As Boolean)
_checkedOut = Value
End Set
End Property
Private _dateOfAcquisition As
DateTime
Public Property
DateOfAcquisition() As DateTime
Get
Return _dateOfAcquisition
End Get
Set(ByVal Value As
DateTime)
_dateOfAcquisition = Value
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
End Set rights reserved.
7
2. Abstraction
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Abstraction
 Abstraction
means ignoring irrelevant features,
properties, or functions and emphasizing the
relevant ones ... Data Abstraction is the development
of classes,
objects, types in terms of their interfaces and
functionality, instead of their implementation
details.
"Relevant" to what?
 ...
relevant to the given project (with an eye to future
reuse in similar projects) Abstraction = managing
complexity
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
9
Inheritance Hierarchies
 Using
inheritance we can create inheritance
hierarchies
– Easily represented by UML class diagrams
 UML
class diagrams
– Classes are represented by rectangles
containing their methods and data
– Relations between classes are shown as arrows


10
Closed triangle arrow means inheritance
Other arrows mean some kind of associations
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
UML Class Diagram – Example
interface
ISurfaceCalculatable
struct
Point
Shape
#Position:Point
+CalculateSurface:float
+X:int
+Y:int
+Point
Square
-Size:float
+Square
+CalculateSurface:float
struct
Color
Rectangle
-Width:float
-Height:float
+Rectangle
+CalculateSurface:float
+RedValue:byte
+GreenValue:byte
+BlueValue:byte
+Color
11
FilledSquare
FilledRectangle
-Color:Color
-Color:Color
+FilledSquare
+FilledRectangle
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Class Diagrams
in
Visual Studio
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
3. Encapsulation
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Encapsulation
 Encapsulation
hides the implementation details
 Class announces some operations (methods)
available for its clients – its public interface
 All data members (fields) of a class should be
hidden Accessed via properties (read-only and
read-write)
 No interface members should be hidden
 Encapsulation in a nutshell, encapsulation is the
hiding of data implementation by restricting
access to accessors and mutators.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
14
Encapsulation – Example
 Data
fields are private
 Constructors and accessors are defined
(getters and setters)
Person
-name : string
-age : TimeSpan
+Person(string name, int age)
+Name : string { get; set; }
+Age : TimeSpan { get; set; }
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
15
Accessor
An accessor is a method that is used to ask an object about itself.
In OOP, these are usually in the form of properties, which have, under
normal conditions, a get method, which is an accessor method.
However, accessor methods are not restricted to properties and can be
any public method that gives information about the state of the object.
Public Class Person
// use Private class to hide the implementation of the objects .
// fullName, which is used for the internal implementation of Person.
Private _fullName As String = “Raymond Lewallen”
/* This property acts as an accessor. To the caller, it hides the implementation of fullName and where it is set and what
is setting its value. It only returns the fullname state of the Person object, and nothing more. From another class,
calling Person.FullName() will return “Raymond Lewallen”.
There are other things, such as we need to instantiate the Person class first, but thats a different discussion.
Public ReadOnly Property FullName() As String
Get
Return _fullName
End Get
End Property
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
End Class
rights reserved.
16
Mutator
Mutators are public methods that are used to modify the state of an
object, while hiding the implementation of exactly how the data
gets modified.
Mutators are commonly another portion of the property discussed
above, except this time its the set method that lets the caller modify
the member data behind the scenes.
Public Class Person
//We use Private here to hide the implementation of the objects
// implementation of Person.
fullName, which is used for the internal
Private _fullName As String = “Raymond Lewallen”
//This property now acts as an accessor and mutator. We still have hidden the implementation of fullName.
Public Property FullName() As String
Get
Return FullName
End Get
Set(ByVal value As String)
_fullName = value
End Set
End Property Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
17
Data abstraction and encapuslation are closely tied
together, because a simple definition of data abstraction is
the development of classes, objects, types in terms of their
interfaces and functionality, instead of their implementation
details Abstraction is used to manage complexity.
Software developers use abstraction to decompose complex
systems into smaller components.
The best definition of abstraction I’ve ever read is: “An
abstraction denotes the essential characteristics of an object
that distinguish it from all other kinds of object and thus
provide crisply defined conceptual boundaries, relative to
the perspective of the viewer.”, G. Booch,
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
18
4. Polymorphism
Polymorphism means that a variable of a supertype can
refer to a subtype object.
 Polymorphism is an important Object oriented concept and
widely used in Java and other programming language.
 Polymorphism in java is supported along with other
concept like Abstraction, Encapsulation and Inheritance.
 Polymorphism means one name, many forms.
 Polymorphism manifests itself by having multiple methods
all with the same name, but slighty different functionality.

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
19
//Magazine class that inherits LibraryAsset
Public NotInheritable Class Magazine
Inherits LibraryAsset
End Class
//Book class that inherits LibraryAsset
Public NotInheritable Class Book
Inherits LibraryAsset
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
20
Polymorphism
 Polymorphism
= ability to take more than one form
(objects have more than one type)
– A class can be used through its parent interface
– A child class may override some of the behaviors of
the parent class
 Polymorphism
allows abstract operations to be
defined and used
– Abstract operations are defined in the base class'
interface and implemented in the child classes
 Declared
as abstract or virtual
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
21
Polymorphism (2)
 Why
handle an object of given type as object of
its base type?
– To invoke abstract operations
– To mix different related types in the same collection
 E.g.
List<object> can hold anything
– To pass more specific object to a method that expects
a parameter of a more generic type
– To declare a more generic field which will be
initialized and "specialized" later
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
22
Polymorphism – Example (2)
abstract class Figure
{
public abstract double CalcSurface();
}
abstract class Square
{
public override double CalcSurface() { return … }
}
Figure f1 = new Square(...);
Figure f2 = new Circle(...);
// This will call Square.CalcSurface()
int surface = f1.CalcSurface();
// This will call Square.CalcSurface()
int surface = f2.CalcSurface();
23
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Inheritance
 When
OOP allows you to design new classes
from existing classes, this process called
inheritance.
 Inheritance is an important and powerful
feature for
• reasoning software;
• avoid redundancy;
• make the system easy to comprehend;
• and easy to maintain.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
24
Superclasses & Subclasses
Inheritance enable to define a general class called
superclass(parent class) and later extend it to
more specialized classes called subclass(child
class). Examples are as follow:
• We can call “EverGreen Trees” are subclass
(child) of the “Trees” superclass(parent).
• An “EmployeeWithTerritory” is a child to the
“Employee” parent.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
25
Concept of Inheritance
Public class Employee
/*the class contain two data field and four
methods, a get & set method for each field.*/
{
private int empNum;
private double empSal;
public int getEmpNum()
{
return empNum;
}
public double getEmpSal()
{
retrun empSal;
}
public void setEmpNum(int num)
{
empNum = num;
}
public void setEmpSal(double sal)
{
empSal = sal;
}
Employee
- empNum : int
- empSal : double
+getEmpNum : int
+getEmpSal : double
+setEmpNum(int num) : void
+setEmpSal(doulbe sal) : void
After create the Employee
class, you can create specific
Employee objects, such as the
following:
Employee receptionist = new Employee();
Employee deliveryPerson = new Employee();
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
26
Class Diagram showing
Employee & EmployeeWithTerritory
Employee
- empNum : int
- empSal : double
EmployeeWithTerritory
+getEmpNum : int
+getEmpSal : double
+setEmpNum(int num) : void
+setEmpSal(doulbe sal) : void
+getEmpTerritory : int
+getEmpTerritory(int territory) : void
-empTerritory : int
Class diagram showing the relationship between Emplyee and
EmployeeWithTerritory.
You create a class, EmployeeWithTerritory, and provide
the class three field (empNum, empSal & empTerritory)
and six methods (get & set methods for each three
fields).
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
27
Class Diagram showing
Employee & EmployeeWithTerritory cont..
Efficient alternative is: create class
EmployeeWithTerritory so it inherits all the
attributes and methods of employee.
Then, you can add just one field and two
methods that are within EmployeeWithTerritory
objects.
Use inheritance to create derived class
 Save time
 Reduce errors
 Reduce amount of new learning required to use new class
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
28
Inheritance Terminology
Base class
Used as a basis for inheritance
Also called:
 Superclass, or Parent class (such as Employee)
Derived class
Inherits from a base class
Always “is a” case or example of more general base
class
Also called:
 Subclass or Child class (Such as EmployeeWithTerritory)
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
29
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
30
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(double d) {
// some statements
}
public A() {
super();
}
is equivalent to
is equivalent to
public A(double d) {
super();
// some statements
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
31
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: boolean)
Creates a GeometricObject with the specified color and filled
values.
+getColor(): String
Returns the color.
+setColor(color: String): void
Sets a new color.
+isFilled(): boolean
Returns the filled property.
+setFilled(filled: boolean): void
Sets a new filled property.
+getDateCreated(): java.util.Date
Returns the dateCreated.
+toString(): String
Returns a string representation of this object.
The GeometricObject class
is the superclass for Circle
and Rectangle
GeometricObject
CircleFromSimpleGeometricObject
Rectangle
Circle
-radius: double
-width: double
+Circle()
-height: double
+Circle(radius: double)
+Rectangle()
+Circle(radius: double, color: String,
filled: boolean)
+Rectangle(width: double, height: double)
+getRadius(): double
+Rectangle(width: double, height: double
color: String, filled: boolean)
+setRadius(radius: double): void
+getWidth(): double
+getArea(): double
+setWidth(width: double): void
+getPerimeter(): double
+getHeight(): double
+getDiameter(): double
+setHeight(height: double): void
+printCircle(): void
+getArea(): double
RectangleFromSimpleGeometricObject
TestCircleRectangle
Run
+getPerimeter(): double
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
32
SimleGeometricObject
Video
 Video
Listing -1 - GeometricObject
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
33
Calling Superclass Methods
You could rewrite the printCircle() method in the Circle class as
follows:
public void printCircle() {
System.out.println("The circle is created " +
super.getDateCreated() + " and the radius is " + radius);
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
34
Overriding Methods in the Superclass
A subclass inherits methods from a superclass. Sometimes it is
necessary for the subclass to modify the implementation of a method
defined in the superclass. This is referred to as method overriding.
public class Circle extends GeometricObject {
// Other methods are omitted
/** Override the toString method defined in GeometricObject */
public String toString() {
return super.toString() + "\nradius is " + radius;
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
35
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
36
Extending Classes
Keyword extends
• Achieve inheritance in Java
• Example:
public class EmployeeWithTerritory extends Employee
• Inheritance is a one-way proposition (plan)
o Child inherits from parent, not other way
around
• Subclasses are more specific
• instanceof keyword
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
37
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());
...
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
38
Extending Classes (cont'd.)
Each EmployeeWithTerritory automatically receives the data
fields and methods of the superclass Employee, then new fields
and methods to the newly created subclass.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
39
Constructor Chaining
Constructing an instance of a class invokes all the superclasses’ constructors
along the inheritance chain. This is called 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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
40
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
41
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
42
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 noarg constructor
}
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
43
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)
constructor
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
44
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
45
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
46
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
47
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
48
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
49
Overriding vs. Overloading
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
class B {
public void p(double i) {
System.out.println(i * 2);
}
}
class B {
public void p(double i) {
System.out.println(i * 2);
}
}
class A extends B {
// This method overrides the method in B
public void p(double i) {
System.out.println(i);
}
}
class A extends B {
// This method overloads the method in B
public void p(int i) {
System.out.println(i);
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
50
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 {
...
}
Equivalent
public class Circle extends Object {
...
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
51
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 a number representing this 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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
52
Polymorphism, Dynamic Binding and Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) {
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
public static void m(Object x) {
System.out.println(x.toString());
}
}
Method m takes a parameter
of the Object type. You can
invoke it with any object.
An object of a subtype can be used wherever its
supertype value is required. This feature is
known as polymorphism.
class GraduateStudent extends Student {
}
When the method m(Object x) is executed, the
argument x’s toString method is invoked. x
may be an instance of GraduateStudent,
Student, Person, or Object. Classes
class Person extends Object {
GraduateStudent, Student, Person, and Object
public String toString() {
return "Person";
have their own implementation of the toString
}
method. Which implementation is used will be
}
determined dynamically by the Java Virtual
DynamicBindingDemo Machine at runtime. This capability is known
as dynamic binding.
class Student extends Person {
public String toString() {
return "Student";
}
}
Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
53
Polymorphism and
Dynamic Binding
 Video
Listing 6 - DynamicBindingDemo
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
54
Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) {
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
public static void m(Object x) {
System.out.println(x.toString());
}
}
class GraduateStudent extends Student {
}
class Student extends Person {
public String toString() {
return "Student";
}
}
Polymorphism allows methods to be used
generically for a wide range of object
arguments. This is known as generic
programming. If a method’s parameter
type is a superclass (e.g., Object), you
may 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 object or a String object) is used
in the method, the particular
implementation of the method of the
object that is invoked (e.g., toString) is
determined dynamically.
class Person extends Object {
public String toString() {
return "Person";
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
55
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
56
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
57
Casting from
Superclass to Subclass
Explicit casting must be used when casting an
object from a superclass to a subclass. This type
of casting may not always succeed.
Apple x = (Apple)fruit;
Orange x = (Orange)fruit;
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
58
Example: Demonstrating
Polymorphism and Casting
This example creates two geometric objects:
a circle, and a rectangle, invokes the
displayGeometricObject method to display
the objects.
The displayGeometricObject displays the
area and diameter if the object is a circle, and
displays area if the object is a rectangle.
CastingDemo
Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
59
public class CastingDemo {
/** Main method */
public static void main(String[] args) {
// Declare and initialize two objects
Object object1 = new Circle4(1);
Object object2 = new Rectangle1(1, 1);
// Display circle and rectangle
displayObject(object1);
displayObject(object2);
}
/** A method for displaying an object */
public static void displayObject(Object object) {
if (object instanceof Circle4) {
System.out.println("The circle area is " +
((Circle4)object).getArea());
System.out.println("The circle diameter is " +
((Circle4)object).getDiameter());
}
else if (object instanceof Rectangle1) {
System.out.println("The rectangle area is " +
((Rectangle1)object).getArea());
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
}
rights reserved.
60
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:
public boolean equals(Object obj) {
return (this == obj);
}
For example, the
equals method is
overridden in
the Circle
class.
public boolean equals(Object o) {
if (o instanceof Circle) {
return radius == ((Circle)o).radius;
}
else
return false;
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
61
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.
+contains(o: Object): boolean
Returns true if this list contains the element o.
+get(index: int) : E
Returns the element from this list at the specified index.
+indexOf(o: Object) : int
Returns the index of the first matching element in this list.
+isEmpty(): boolean
Returns true if this list contains no elements.
+lastIndexOf(o: Object) : int
Returns the index of the last matching element in this list.
+remove(o: Object): boolean
Removes the element o from this list.
+size(): int
Returns the number of elements in this list.
+remove(index: int) : boolean
Removes the element at the specified index.
+set(index: int, o: E) : E
Sets the element at the specified index.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
62
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>();
TestArrayList
Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
63
Differences and Similarities between
Arrays and ArrayList
Operation
Array
ArrayList
Creating an array/ArrayList
String[] a = new String[10]
ArrayList<String> list = new ArrayList<>();
Accessing an element
a[index]
list.get(index);
Updating an element
a[index] = "London";
list.set(index, "London");
Returning size
a.length
list.size();
Adding a new element
list.add("London");
Inserting a new element
list.add(index, "London");
Removing an element
list.remove(index);
Removing an element
list.remove(Object);
Removing all elements
list.clear();
DistinctNumbers
Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
64
The MyStack Classes
A stack to hold objects.
MyStack
MyStack
-list: ArrayList
A list to store elements.
+isEmpty(): boolean
Returns true if this stack is empty.
+getSize(): int
Returns the number of elements in this stack.
+peek(): Object
Returns the top element in this stack.
+pop(): Object
Returns and removes the top element in this stack.
+push(o: Object): void
Adds a new element to the top of this stack.
+search(o: Object): int
Returns the position of the first element in the stack from
the top that matches the specified element.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
65
The protected Modifier
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.
 The
 private,
default, protected, public
Visibility increases
private, none (if no modifier is used), protected, public
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
66
Accessibility Summary
Modifier
on members
in a class
Accessed
from the
same class
Accessed
from the
same package
Accessed
from a
subclass
Accessed
from a different
package
public
-
protected
default
private
-
-
-
-
-
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
67
Visibility Modifiers
package p1;
public class C1 {
public int x;
protected int y;
int z;
private int u;
public class C2 {
C1 o = new C1();
can access o.x;
can access o.y;
can access o.z;
cannot access o.u;
protected void m() {
}
}
can invoke o.m();
}
package p2;
public class C3
extends C1 {
can access x;
can access y;
can access z;
cannot access u;
public class C4
extends C1 {
can access x;
can access y;
cannot access z;
cannot access u;
can invoke m();
}
public class C5 {
C1 o = new C1();
can access o.x;
cannot access o.y;
cannot access o.z;
cannot access o.u;
can invoke m();
}
cannot invoke o.m();
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
68
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
69