INHERITANCE IN JAVA
Dr. Dieaa I. Nassr
&
Dr. Mohammad Hashim
Computer Science Division, Mathematics Department, Faculty of Science,
Ain Shams university
1
Inheritance
• One of the main techniques of OOP is known as inheritance.
• Inheritance means that a very general form of a class can be defined and compiled, and
then more specialized versions of that class may be defined by starting with the already
defined class and adding more specialized instance variables and methods.
• The specialized classes are said to inherit the methods and instance variables of the
previously defined general class.
2
Inheritance
• In Java, Inheritance is the process by which a new class — known as a derived class or
subclass — is created from another class, called the base class or super class.
• A derived class automatically has all the instance variables and all the methods that the base
class has, and can have additional methods and/or additional instance variables.
• Inheritance allows an object of a derived class to acquire the properties of that object of the
base class.
• Without the use of inheritance; each object needs to define all of its characteristics explicitly.
• Inheritance ensures the concept of code reusability which is the main aim of the Object
Oriented Programming methodology.
3
Inheritance
• Derived class = child class = subclass
• Base class = parent class = superclass
• The importance of inheritance is it supports the concept of hierarchical classification.
• The relation between a derived class and base class is know as “is-a” relationship.
• If class A is derived from base class B, then we can say that
“A is-a B”
5
Inheritance (Syntax)
modifier(s) class ClassName extends ExistingClassName
{
memberList
}
6
In which cases do we need the design of a base class and many other
subclasses? Whenever there are shared features among these subclasses.
Example: Shared Functionality
public class Student { public class Professor {
String name; String name;
char gender; char gender;
Date birthday; Date birthday;
double []grades; Paper []papers;
double getGPA() { int getCiteCount() {
… …
} }
int getAge(Date today) { int getAge(Date today) {
… …
} }
} }
7
public class Person {
String name;
char gender;
Date birthday;
int getAge(Date today) {
…
}
}
public class Student public class Professor
extends Person { extends Person {
double []grades; Paper []papers;
double getGPA() { int getCiteCount() {
… …
} }
} }
8
Code Reuse
• General functionality can be written once and applied to *any*
subclass
• Subclasses can specialize by adding members and methods, or
overriding functions
9
Inheritance: Adding Functionality
• Subclasses have all of the data members and methods of the
superclass
• Subclasses can add to the superclass
❑Additional data members
❑Additional methods
• Subclasses are more specific and have more functionality
• Superclasses capture generic functionality common across
many types of objects
10
public class Person {
String name;
char gender;
Date birthday;
int getAge(Date today) {
…
}
}
public class Student public class Professor
extends Person { extends Person {
double []grades; Paper []papers;
double getGPA() { int getCiteCount() {
… …
} }
} }
11
UML Diagram: Rectangle
What if we want to implement a 3d box object?
13
UML Class Diagram: class Box
Both a Rectangle and a Box have an area (surface area for box),
but they are computed differently
14
Objects myRectangle and myBox
Rectangle myRectangle = new Rectangle(5, 3);
Box myBox = new Box(6, 5, 4);
15
Method Overloading in Java
• If a class has multiple methods having same name but different in parameters, it
is known as Method Overloading.
• Method overloading increases the readability of the program.
• There are two ways to overload the method in java
• By changing number of arguments
• By changing the data type of the arguments
• In java, method overloading is not possible by changing the return type of the
method only because of ambiguity.
• From the last example; class Box has overloading for the method setDimention:
• The defined one inside the Box (with 3 arguments)
• The inherited one form class Rectangle (with 2 arguments)
16
Method Overriding
• If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in Java.
• Method overriding is used to provide the specific implementation of
a method which is already provided by its superclass.
• A subclass can override (redefine) the methods of the
superclass
• Objects of the subclass type will use the new method
• Objects of the superclass type will use the original
• Method overriding is mostly used in Runtime Polymorphism which
we will learn in next lecture. 17
Rules for Java Method
Overriding
• The method must have the same name as in the parent
class
• The method must have the same parameter as in the
parent class.
• There must be an IS-A relationship (inheritance).
• The method must not be more restrictive (using access
modifiers).
❑ private is the most restrictive access modifier
❑ public is the least restrictive access modifier
18
Example for Java Method Overriding
class Rectangle
public double area()
{
return getLength() * getWidth();
}
class Box
public double area()
{
return 2 * (getLength() * getWidth()
+ getLength() * height
+ getWidth() * height);
} 19
20
• The covariant return type specifies that the return
type may vary in the same direction as the
subclass.
• Before Java5, it was not possible to override any
method by changing the return type.
• Since Java5, it is possible to override method by
changing the return type if subclass overrides any
method whose return type is Non-Primitive but it
Covariant Return changes its return type to subclass type.
Type • For example:
21
• The super keyword in Java is a reference variable which is used
to refer immediate parent class object.
• Whenever you create the instance of subclass, an instance of
parent class is created implicitly which is referred by super
reference variable.
• Usage of Java super Keyword:
Super Keyword • super can be used to refer
in Java immediate parent class instance
variable.
• super can be used to invoke
immediate parent class method.
• super() can be used to invoke
immediate parent class
constructor.
22
Using super to refer immediate parent class instance variable
• We can use super keyword to access the data member or field of parent class.
• It is used if parent class and child class have same fields.
23
Using super to refer immediate parent class methods
• To write a method’s definition of a subclass, specify a call to the
public method of the superclass
• If subclass overrides public method of superclass, specify call to public
method of superclass:
super.MethodName(parameter list)
• If subclass does not override public method of superclass, specify call to
public method of superclass:
MethodName(parameter list)
In this case the super keyword is optional
24
class Box
public void setDimension(double l, double w, double h)
{
super.setDimension(l, w);
if (h >= 0)
height = h;
else
height = 0;
}
}// class end
Box overloads the method setDimension
(Different parameters)
25
class Rectangle
public double area()
{
return getLength() * getWidth();
}
class Box
public double area()
{ super.area()
return 2 * (getLength() * getWidth()
+ getLength() * height
+ getWidth() * height);
}
26
Using super to invoke parent class constructor
• Call to constructor of superclass:
• Must be first statement
• Specified by super parameter list
public Box()
{
super();
height = 0;
}
public Box(double l, double w, double h)
{
super(l, w);
height = h;
}
27
Important Notes:
• The default constructor is provided by compiler automatically if there is no constructor. But, if
the class has already any constructors, the compiler will not provide any constructors.
• super() is added in each class constructor automatically by compiler if there is no super() or this().
This will call the default constructor (non-arguments constructor) of the super class.
28
Types of Inheritance
Supported in Java Not Supported in Java
29
Why multiple inheritance is
not supported in java?
• To reduce the complexity and to simplify the
language, multiple inheritance is not supported in
java.
• Consider a scenario where A, B, and C are three
classes. The C class inherits from A and B classes
directly. If A and B classes have the same method
and you call it from child class object, there will be
ambiguity to call the method of A or B class.
• Since compile-time errors are better than runtime
errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same
method or different, there will be compile time
error.
30
Inheritance and Access Modifiers
• Each instance member (data or method) at the superclass are inherited to the subclass, but
the accessibility of them differs as shown below:
31
Composition and Aggregation
• Another way to relate two classes
• One or more members of a class are objects of another class type
• “has-a” relation between classes
• For example, “every person has a date of birth”
• We use it for code reusability when there is no “is-a” relation.
• In aggregation, both classes can survive individually, which means ending one class
will not effect the other class.
• Composition is a restricted form of Aggregation in which two classes are highly
dependent on each other.
• It represents part-of relationship.
• Both classes are dependent on each other.
• The composed class cannot exist without the other entity. 32
Aggregation vs Composition
❑Dependency:
• Aggregation implies a relationship where the child can exist independently of the parent.
• For example, Bank and Employee, delete the Bank and the Employee still exist.
• Composition implies a relationship where the child cannot exist independent of the parent.
• For example: Human and heart, heart don’t exist separate to a Human
❑Type of Relationship:
• Aggregation relation is “has-a”
• Composition is “part-of” relation.
❑Type of association:
• Aggregation is a weak Association.
• Composition is a strong Association 33
The final Modifier
• The final modifier in java is used to restrict the
user.
• The java final modifier can be used in many
context:
1. Variable (no change in value ≡ constant)
2. Method (no override allowed)
3. Class (no inheritance)
34
Notes:
• The final variable can be either:
• Class data member
• Local variable
• A final variable that is not initialized at the time of declaration is known as blank final
variable or uninitialized final variable.
• It is used to create a variable that is initialized at the time of creating object, and once initialized
may not be changed (for example: studentID)
• It can be initialized in the constructor only.
• The blank final variable can be static also which will be initialized in the static block only (for
example: maxDegree).
• A final method is inherited but you cannot override it.
• Class String is a final class.
35
final Methods
• Can declare a method of a class final using the keyword final
public final void doSomeThing()
{
//...
}
• If a method of a class is declared final, it cannot be overridden with a new
definition in a derived class
36
Notes:
• If you declare any parameter as final, you cannot change its value.
• For example:
int cube(final int n) {
n = n + 2; //Compiler error
return n*n*n;
}
• A constructor can not be neither final nor static.
• When a variable declared to be public final static, then its naming
convention is to be written in upper case.
• For example: Math.PI , Math.E, Integer.MAX_VALUE
37
The Object class
• Java applies the inheritance concept in its classes using the class
Object.
• There is one special class, Object, defined by Java. All other classes
are subclasses of Object.
• That is, Object is a superclass of all other classes. This means that a
reference variable of type Object can refer to an object of any other
class. Also, since arrays are implemented as classes, a variable of type
Object can also refer to any array.
• Object defines the following methods, which means that they are
available in every object:
38
Methods of
Class
Object
39
• You may override these methods in your class (except getClass( ),
notify( ), notifyAll( ), and wait( ) because they are declared as final)
• The equals( ) method compares the contents of two objects. It returns
true if the objects are equivalent, and false otherwise.
• The precise definition of equality can vary, depending on the type of objects being
compared.
• The toString( ) method returns a string that contains a description of
the object on which it is called. Also, this method is automatically
called when an object is output using println( ).
• Many classes override this method. Doing so allows them to tailor a description
specifically for the types of objects that they create.
40