OOP Ch05 Inheritance and Polymorphism
OOP Ch05 Inheritance and Polymorphism
is a is a
Student
Professor
- String studentId, majorField
- String department
- String degreeSought
+ String getDepartment(); teach
+ String getStudentId();
+ void setDepartment(String d);
+ void setStudentID(String id)
….
The class Professor has the field The class Student has the
Student[] students field Professor pr
Inheritance
• How to construct a class hierarchy? → Intersection
⚫ Rectangle< length, width>
⚫ Box < length, width, height> Rectangle
Length
width
Box
height
Inheritance…
• Consider a shop that sells antiques items, namely vases, statues and
paintings
Inheritance…
• There are some sub-classes from one super class ➔ An inheritance is
a relationship where objects share a common structure: the structure
of one object is a sub-structure of another object.
• The extends keyword is used to create sub-class.
• A class can be directly derived from only one class
( Java is a single-inherited OOP language).
• If a class does not have any superclass, then it is implicitly derived
from Object class.
• Unlike other members, constructor cannot be inherited (constructor of
super class can not initialize sub-class objects)
“super” Keyword
• Constructors Are Not Inherited
• super(...) for Constructor Reuse
• super(arguments); //invoke a superclass constructor
• Subclass constructor must invoke super class constructor
• The call must be the first statement in the
subclass constructor
• Note: If a constructor does not explicitly invoke a superclass constructor,
the Java compiler automatically inserts a call to the no-argument
constructor of the superclass. If the super class does not have a no-
argument constructor, you will get a compile-time error.
Example
Example…
public class Point {
Example…
private int x,y;
public Point(int x,int y){
this.x=x; this.y=y;}
…..//getter & setter }
public class Polygon {
protected Point d1, d2, d3, d4;
public void setD1(Point d1) {this.d1=d1;}
public Point getD1(){return d1;}
@Override
public String toString(){
return
d1.getX()+"\t"+d1.getY()+"\t"+d2.getX()+"\t"+d2.getY()+
"\t"+d3.getX()+"\t"+d3.getY()+"\t"+d4.getX()+"\t"+d4.getY(); }}
public class Square extends Polygon{
public Square(){
d1 = new Point(0,0); d2 = new Point(0,1);
d3 = new Point (1,0);d4 = new Point(1,1);
}
}
public class Main {
public static void main(String args[]){
Square sq = new Square();
System.out.println(sq.toString());
}
}
public class Main {
public static void main(String
args[]){
Employee e = new Employee();
public class Person {
e.setName("To Ngoc Van");
private String name;
e.setBithday("3/4/1994");
private String bithday;
e.setSalary(4.4);
public Person() { System.out.println(e.toString());
} // getter & setter } }
public class Employee extends Person }{
private double salary;
public double getSalary() { return salary; }
public void setSalary(double salary){
this.salary = salary; }
@Override
public String toString() {
//return name + "\t" + birthday + "\t" + salary;
return super.getName() + "\t" + super.getBithday() +
"\t" + salary;
}
}
1. public class Polygon { Output???
protected Point d1, d2, d3, d4;
public Polygon() {
System.out.println(“Polygon class");
}……}
2. public class Square extends Polygon{
public Square(){
System.out.println(“Square class");
}
}
3. public class Main {
public static void main(String args[]){
Square hv = new Square();
}
}
1. public class Polygon {
protected Point d1, d2, d3, d4;
//a constructor is not default contructor
……}
2. public class Square extends Polygon{
public Square(){
System.out.println(“Square class");
}
}
3. public class Main {
public static void main(String args[]){
Square hv = new Square();
}
}
Why Error???
Functions in inheritance
• A derived class inherits from superclass is limited to the normal member
functions of the superclass.
• We use the Java keyword super as the qualifier for calling a superclass ’s method:
• super.methodName(arguments);
• To invoke the version of method methodName that was defined by our
superclass.
• Hiding a method: Re-implementing a static method implemented in super class
• The "displayDiscount" method has the
same signature (name, plus the number
and the type of its parameters) and return
type as in the superclass. It is called
Output:
overriding the superclass's method=> We
discounting …
will learn override method in the next topic
and taking …
• The "displayDiscount") that was defined by
our superclass. We use
the "super" keyword
Overriding and Hiding Methods (1)
• Overriding a method: An instance method in a subclass with the
same signature (name, plus the number and the type of its
parameters) and return type as an instance method in the superclass
overrides the superclass's method.
• Use the @Override annotation that instructs the compiler that you intend to
override a method in the superclass (you may not use it because overriding is
default in Java).
• Hiding a method: Re-implementing a static method implemented in
super class
Hiding Method
Using an “instanceof” operator
• Dynamic and Static type
▪ dynamic type: A reference variable that has the type of the superclass
can store the address of the object of sub class. It is called to
be dynamic type, the type that is has at runtime.
Rectangle obj1 = new Box();
▪ Static type: The type that it has when first declared. Static type checking
is enforced by the compiler.
Box obj2 = new Box();
• “Instanceof” operator: It checks whether the reference of an object
belongs to the provided type or not, the instanceof operator will return
true or false.
If ( obj1 instanceof Box)
System.out.println(“ obj1 is pointing to the Box object”);
Casting
• A variable that has the type of the superclass only calls methods of
the superclass. To call methods of the subclass we must cast explicitly
• for example,
Rectangle obj = new Box();
((Box)obj).setHeight(300);
Polymorphism
• The dictionary definition of polymorphism refers to a principle in
biology in which an organism or species can have many different
forms or stages.
• Polymorphism was perfected in object-oriented languages
• Ability allows many versions of a method based on overloading
and overriding methods techniques.
• Overloading: A class can have some methods which have the
same name but their parameter types are different.
• Overriding: A method in the father class can be overridden in
its derived classes (body of a method can be replaced in
derived classes).
Overloading
• overloading with constructors
public Rectangle(){…}
Rectangle
public Rectangle(int length,
# length: int int width){… }
# width: int
• Overloading also extends to general methods.
+ Rectangle();
public void setValue(int len){
+ Rectangle(int, int) length= (len>0)?1:0;
+ setValue(int): void }
+ setValue(int, int): void public void setValue (int len,
int wi){
length= (len>0)? 1: 0;
width= (wi>0)? wi:0;
}
Overriding
• A subclass provides the specific implementation of the method that
has been declared by one of its pare
• Subclasses of a class can define their own unique behaviors and yet
share some of the same functionality of the parent class.
Student
- String name;
+ void print();
GraduateStudent UndergraduateStudent
Output:
set lock in the default method
on TV
off TV
shut down after 10000 seconds
TV remote's price:10
TV Remote has: 20buttons
increase volumn
Example: how to extend interfaces
Output:
on AC
display Korean
set lock in the
default method
Abstract Classes
• Used to define what behaviors a class is required to perform without
having to
provide an explicit implementation.
• It is the result of so-high generalization
• Syntax to define a abstract class
• public abstract class className{ ... }
• It isn’t necessary for all of the methods in an abstract class to be
abstract.
• An abstract class can also declare implemented methods.
Abstract Classes…
Modified
Abstract Classes…
Error. Why?
Implementing Abstract Methods
• Derive a class from an abstract superclass, the subclass will inherit all
of the superclass’s
features, all of abstract methods included.
• To replace an inherited abstract method with
a concrete version, the subclass need merely override it.
• Abstract classes cannot be instantiated
Anonymous Classes
Anonymous classes are classes which are not named but they are
identified automatically by Java compiler.
Where are they? They are identified at initializations of
interface/abstract class object but abstract methods are implemented
as attachments.
Why are they used?
• Enable you to make your code more concise.
• Enable you to declare and instantiate a class at the same time.
• They are like local classes except that they do not have a name.
• Use them if you need to use a local class only once.
Anonymous Class
Anonymous class.