Java Module 3
Java Module 3
MODULE III
MODULE III
Contents
Inheritance
Inheritance Basics
Using super
Creating a Multilevel Hierarchy
When Constructors Are Executed
Method Overriding
Dynamic Method Dispatch
Using Abstract Classes
Using final with Inheritance
Local Variable Type Inference and Inheritance
The Object Class
Interfaces
Interfaces
Default Interface Methods
Use static Methods in an Interface
Private Interface Methods
Inheritance
Inheritance is one of the cornerstones of object-oriented programming because it
allows the creation of hierarchical classifications. Using inheritance, you can create a general
class that defines the traits common to a set of related items. This class can then be inherited
by other, more specific classes, each adding those things that are unique to it. In the
terminology of Java, a class that is inherited is called a Superclass. The class that does the
inheriting is called a subclass.
Inheritance Basics
To inherit a class, you simply incorporate the definition of one class into another by
using the extends keyword. If we say class A extends B, means B is the superclass and A is
the extension of B.
1
Object-Oriented Programming with JAVA: BCS306A
MODULE III
Demonstration of Inheritance
public class A {
int i;
int j;
void showij() {
System.out.println("i and j is " + i + " " +
j);
}
}
public class B extends A {
int k;
void showk() {
System.out.println(" The k is " + k);
}
void sum() {
System.out.println(" The sum is " + (i+j+k));
}
}
public class SimpleInheritanceDemo {
subobj.i=45;
subobj.j=60;
subobj.k=75;
subobj.sum();
}
2
Object-Oriented Programming with JAVA: BCS306A
MODULE III
3
Object-Oriented Programming with JAVA: BCS306A
MODULE III
4
Object-Oriented Programming with JAVA: BCS306A
MODULE III
}
A Closer Look at the Program
Here we have three classes
One class called Box.
In the Box class we have only three instance variables width, height, and breadth
BoxWeight class is the inheritance of the class called Box
In BoxWeight class we have another instance variable called weight
In the DemoBoxWeight class we can access the methods from both the Box class and
BoxWeight class.
5
Object-Oriented Programming with JAVA: BCS306A
MODULE III
6
Object-Oriented Programming with JAVA: BCS306A
MODULE III
Using Super
A subclass can call a constructor defined by its superclass by use of the following
form of super – super(arg – list).To see how super() is used, consider the demonstration
program on ‘Demonstration of Overriding’.
Method Overriding
If a subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java. In other words, if a subclass provides the specific
implementation of the method that has been declared by one of its parent class, it is known as
method overriding. Automatically readers will get doubt in the understanding between
overloading and overriding. The following table helps in a better understanding of these two
terms.
Overriding Overloading
Implements “runtime polymorphism” Implements “compile time polymorphism”
The method call is determined at runtime The method call is determined at compile
based on the object type time.
Occurs between superclass and subclass Occurs between the methods in the same
class.
Have the same signature (name and method Have the same name, but the parameters are
arguments) different
On error, the effect will be visible at runtime On error, it can be caught at compile time.
Demonstration of Overriding
public class A {
//Here class A (parent class) and a method called show is
created
int i, j;
A(int a, int b){
i=a;
j=b;
}
void show() {
System.out.println("i and j are " + i + " " + j);
}
}
public class B extends A{
//Here a child class B is created with a parent as A
7
Object-Oriented Programming with JAVA: BCS306A
MODULE III
int k;
B(int a, int b, int c){
//Using the super keyword we are initiating the values from
the superclass
super(a,b);
k=c;
}
void show() {
super.show(); /*This will execute the methods in the
superclass.
Also, we can create the objects for class A and Perform the
task show() on class A*/
}
}
public class ClassOverride {
8
Object-Oriented Programming with JAVA: BCS306A
MODULE III
Demonstration of Program
public class Figure {
int dim1;
int dim2;
Figure(int a, int b){
dim1=a;
dim2=b;
}
int area() {
// Here just we want to demonstrate there is no action
happening in the method called area
System.out.println("The figure is undefined");
return 0;
}
}
public class Rectangle extends Figure{
Rectangle(int a, int b){
super(a, b);
}
int area() {//area() is overriding
System.out.println("Area of the rectangle is ");
return dim1 * dim2;
}
}
public class Triangle extends Figure{
Triangle(int a, int b){
//A constructor is created and values are taken from
the superclass Figure
super(a,b);
}
//overriding the area() which is defined in the superclass
Figure in the next line
int area() {
System.out.println("The area of the triangle is ");
return (dim1*dim2)/2;
}
9
Object-Oriented Programming with JAVA: BCS306A
MODULE III
}
//Demonstrate how the child classes Rectangle and Triangle are
accessing the parent class Figure
public class FindArasOfAllClasses {
}
}
A Closer Look at the Program
Figure is the superclass with a method area()
The classes Rectangle and Triangle are the child Classes
The child classes Access the instance variables defined in the parent class using the
super keyword.
Parent class is not accepting any values, so it displays the area as 0
The child classes are accepting the value through the constructors.
Abstraction in Java
In the Object-oriented programming paradigm, abstraction is a process of hiding the
implementation details from the user, only the needed information will be provided to the
user without exposing internal implementation details. The user will have information on
what the object does but the user will never know about how it does.
A real-life example of abstraction is car steering. As a car driver, we know that when we turn
the car steering left, the car will turn left side and when we turn the car steering right, the car
will turn right side. However, we don't know the details of how the car steering system works
internally. By defining the abstract turning behaviours of car steering, car manufacturers
abstracted the internal complexities of the steering system.
10
Object-Oriented Programming with JAVA: BCS306A
MODULE III
With abstraction in place, car manufacturers can implement different steering technologies,
without changing the expected behaviours of car steering systems. As long as the car turns
right or left when the driver turns steering right or left respectively, a driver need not worry
about the internal steering technology of the car.
Data abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved by either using abstract classes or
interfaces. (which will be learned in the upcoming chapter).
Abstract class: is a restricted class that cannot be used to create objects (to access it,
it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods.
We cannot create objects of abstract classes in Java.
11
Object-Oriented Programming with JAVA: BCS306A
MODULE III
}
int area() {
//System.out.println("The area of rectangle is ");
return dim1*dim2;
}
}
class Triangle extends Figure {
Triangle(int a, int b){
super(a,b);
}
int area() {
//System.out.println("The area of Triangle is ");
return (dim1*dim2)/2;
}
}
class DemoAbstractClass {
public static void main(String[] args) {
Rectangle objectr= new Rectangle(4,7);
Triangle obectt=new Triangle(10,20);
Figure refer;
refer=objectr;
System.out.println("The area of rectangle is " +
refer.area());
refer=obectt;
System.out.println("The area of triangle is " +
refer.area());
}
}
A Closer Look at the Program
Here we have a class called Figure which is defined as an abstract class.
This class has only instance variables and a method called area() which does not have
a body.
Next, we have created two inheritance classes called Rectangle and Triangle which
are inherited from the class Figure.
The class Rectangle has accessed the instance variable from the abstract class Figure
with the help of the keyword ‘Super’.
Also, the same method name has been called from the abstract class and created the
body of the method in the Class Rectangle.
In the class Triangle also called the instance variables from the abstract class with the
help of super keyword.
Also created the body of the method area().
12
Object-Oriented Programming with JAVA: BCS306A
MODULE III
In the class DemoAbstractClass we have created the objects for the classes Triangle
and Rectangle and activated the methods.
The final keyword is a non-access modifier used for classes, attributes, and methods,
which makes them non-changeable (impossible to inherit or override). The final keyword
is useful when you want a variable to always store the same value, like PI (3.14159...).
While method overriding is one of Java’s most powerful features, there will be times
when you want to prevent it from overriding. To disallow a method from being overridden,
specify the final as a modifier at the start of its declaration. Methods declared as final cannot
be overridden.
class AAAA {
final void method() {
System.out.println("This cannot be overridden");
}
}
class BBB extends AAAA{
void method(); //This line is showing an error Since it
is defined as a final in the superclass
//Also, if we write the final class AAAA, then we cannot
execute the code "class BBB extends AAAA"
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
A Closer Look at the Program
Here class AAAA has a method that is defined as the final
The Class BBB is the inheritance of class AAAA
Since We have defined the method() in AAAA a final when we try to use the
same in the inheritance class BBB, it will show the error message, since it will
not allow the overriding.
13
Object-Oriented Programming with JAVA: BCS306A
MODULE III
Sometimes you will want to prevent a class from being inherited. To do this, precede
the class declaration with the final. Declaring a class as final implicitly declares all of its
methods as final, too. It is illegal to declare a class as abstract and final since an abstract class
is incomplete by itself and relies upon its subclasses to provide complete implementation.
Note: For implementation code please refer to the previous program.
There is one special class, object, defined by Java. All other classes are subclasses of
Object. That is, the Object is an upper class 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 refer to an array.
14
Object-Oriented Programming with JAVA: BCS306A
MODULE III
hashCode() method
equals(Object obj) method
finalize() method
getClass() method
clone() method
wait(), notify(), notifyAll() methods
toString() method
The toString() provides a String representation of an object and is used to convert an
object to a String. The default toString() method for class Object returns a string consisting
of the name of the class of which the object is an instance, the at-sign character `@’, and
the unsigned hexadecimal representation of the hash code of the object. In other words, it is
defined as:
// Default behaviour of toString() is to print class name, then
// @, then unsigned hexadecimal representation of the hash code
// of the object
public String toString()
{
return getClass().getName() + "@" +
Integer.toHexString(hashCode());
}
It is always recommended to override the toString() method to get our String
representation of Object.
hashCode() method
For every object, JVM generates a unique number which is a hash code. It returns
distinct integers for distinct objects. A common misconception about this method is that the
hashCode() method returns the address of the object, which is not correct. It converts the
internal address of the object to an integer by using an algorithm. The hashCode() method
is native because in Java it is impossible to find the address of an object, so it uses native
languages like C/C++ to find the address of the object.
15
Object-Oriented Programming with JAVA: BCS306A
MODULE III
getClass() method.
It returns the class object of “this” object and is used to get the actual runtime class
of the object. It can also be used to get metadata of this class. The returned Class object is
the object that is locked by static synchronized methods of the represented class. As it is
final, we don’t override it.
finalize() method
This method is called just before an object is garbage collected. It is called
the Garbage Collector on an object when the garbage collector determines that there are no
more references to the object. We should override the finalize() method to dispose of
system resources, perform clean-up activities, and minimize memory leaks. For example,
before destroying the Servlet objects web container, always call the finalize method to
perform clean-up activities of the session.
clone() method
It returns a new object that is the same as this object .
wait(), notify(), notifyAll() methods
Interfaces:
Using the keyword interface, you can fully abstract a class’s interface from its
implementation.
That is, using the interface, you can specify what a class must do, but not how it does
it. Interfaces are syntactically similar to classes, but they lack instance variables, and
their methods are declared without any body.
In practice, this means that you can define interfaces that don’t make assumptions
about how they are implemented.
Once it is defined, any number of classes can implement an interface. Also, one class
can implement any number of interfaces.
To implement an interface, a class must create the complete set of methods defined by
the interface. However, each class is free to determine the details of its own
implementation.
By providing the interface keyword, Java allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism.
16
Object-Oriented Programming with JAVA: BCS306A
MODULE III
Consider two classes , Base1 and Base2, and also consider a Derived class, which in
inheriting the properties from Base1 and Base2.
Base2
Base1
Int a=20
Int a=10
int
Derived Class
If we try to access the variable a with the help of the Derived class, ambiguity problem during
compilation (ambiguity means issues that are not defined clearly in Java language
specification.). So, an interface can be used to access multiple inheritance. Also, it is used for
abstraction, that is showing essential details, but hiding which are not known to others. If we
use interfaces, we can implement abstraction. In the interface, only the declaration of
methods is possible, but the definition of methods is hidden.
When we compare with the abstract class, the abstract class may contain abstract
methods and also normal methods, so everything will be visible to all.
17
Object-Oriented Programming with JAVA: BCS306A
MODULE III
Defining an Interface:
{ return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
When no access specifier is included, then default access results, and the interface is
only available to other members of the package in which it is declared.
When it is declared as public, the interface can be used by any other code.
In this case, the interface must be the only public interface declared in the file, and the
file must have the same name as the interface.
name is the name of the interface, and can be any valid identifier.
Notice that the methods that are declared have no bodies. They end with a semicolon
after the parameter list.
They are, essentially, abstract methods; there can be no default implementation of any
method specified within an interface.
Each class that includes an interface must implement all of the methods.
Variables can be declared inside of interface declarations.
They are implicitly final and static, meaning they cannot be changed by the
implementing class. They must also be initialized.
All methods and variables are implicitly public.
Implementing Interfaces:
Once an interface has been defined, one or more classes can implement that
interface.
18
Object-Oriented Programming with JAVA: BCS306A
MODULE III
You can declare variables as object references that use an interface rather than a class
type.
Any instance of any class that implements the declared interface can be referred to by
such a variable.
When you call a method through one of these references, the correct version will be
called based on the actual instance of the interface being referred to. This is one of the
key features of interfaces.
The method to be executed is looked up dynamically at run time, allowing classes to
be created later than the code that calls methods on them.
The calling code can be dispatched through an interface without having to know
anything about the “callee.
interface A{
int a=20;
void show();
}
interface B{
int a=25;
void show();
}
class C implements A, B
{
public int c;
public void show() {
c=A.a + B.a;
19
Object-Oriented Programming with JAVA: BCS306A
MODULE III
System.out.println(c);
System.out.println(A.a);
System.out.println(B.a);
}
}
public class Test {
Let us understand this concept with an example. Assume that you are a Java developer
and A customer named Arun needs code for addition and another customer named Anjan
needs the code for both addition and subtraction. So first we will create an interface for Arun
and keep the method name add() for Arun. Since Anjan wants both addition and subtraction,
we extend the interface that we have created for Arun. So in the new interface created for
Anjan, we create an additional method subtraction and do with the keyword extends. So that
we do not have to write the code for addition again which we have created for Arun.
20
Object-Oriented Programming with JAVA: BCS306A
MODULE III
interface Arun {
void add();
}
interface Anjan extends Arun{
void subtract();
/*with this interface
Anjan can access both the methods add and subtract*/
}
public class Ankit implements Anjan {
public void add() {
int a=10;
int b=20;
int c;
c=a+b;
System.out.println("The sum is “ + c);
}
public void subtract() {
int a=10;
int b=20;
int c;
c=a-b;
System.out.println("The difference is “ + c);
}
}
public class TestinterfaceExample2 {
public static void main(String[] args) {
Arun ref =new Ankit();
ref.add();
Anjan ref1= new Ankit();
ref1.add();
ref1.subtract();
}
}
https://www.youtube.com/watch?v=_FrzZO2KElc – Link for understanding Extending interface
Default Methods in Interfaces
Before Java 8, we could only declare abstract methods in an interface. However, Java
8 introduced the concept of default methods. Default methods are methods that can have a
21
Object-Oriented Programming with JAVA: BCS306A
MODULE III
body. The most important use of default methods in interfaces is to provide additional
functionality to a given type without breaking down the implementing classes.
Before Java 8, if a new method was introduced in an interface, then all the implementing
classes used to break. We would need to provide the implementation of that method in all the
implementing classes.
However, sometimes methods have only a single implementation and there is no need to
provide their implementation in each class. In that case, we can declare that method as a
default in the interface and provide its implementation in the interface itself.
}
/* Assume that a developer wants to add a method called
speed() to both the classes.
with the same implementation. So we will add default method
speed*/
public class Car implements Vehicles{
public void horn() {
System.out.println("Car Horn Sound");
}
}
public class TestVehiclesInterface {
}
}
22
Object-Oriented Programming with JAVA: BCS306A
MODULE III
Two classes called car and Bike which will be implementing the methods available in
interface vehicles.
Next suddenly the developer wants to add a method called speed(), which will be
implemented in all the classes.
In this case we can define the method called speed() as a default method in the
interface with the method body, which has to be implemented in all the classes.
Otherwise, we have to define the method Speed() in all the classes. If the number of
classes is more, typing of this method takes a longer time.
Since we have defined the Speed() method as default we can create the objects in each
class directly.
Also, it gives an option to change the content of the speed() method depending of the
requirements in each class.
https://www.youtube.com/watch?v=XhNeSRx0lH4
Assume that in the above program the method called Speed() is common for all the classes
and objects has to be created. Then instead of the default method we can use the Static
method.
Partial Implementations
If a class includes an interface but does not fully implement the methods defined by
that interface, then that class must be declared as abstract.
Nested Interfaces
23
Object-Oriented Programming with JAVA: BCS306A
MODULE III
interface Arun {
void add();
}
interface Anjan extends Arun{
void subtract();
/*with this interface
Anjan can access both the methods add and subtract*/
}
public class Ankit implements Anjan {
public void add() {
int a=10;
int b=20;
int c;
c=a+b;
System.out.println("The sum is " + c);
}
public void subtract() {
int a=10;
int b=20;
int c;
c=a-b;
System.out.println("The difference is " + c);
}
}
public class TestinterfaceExample2 {
public static void main(String[] args) {
Arun ref =new Ankit();
ref.add();
Anjan ref1= new Ankit();
ref1.add();
ref1.subtract();
24
Object-Oriented Programming with JAVA: BCS306A
MODULE III
}
}
Variables in Interfaces
You can use interfaces to import shared constants into multiple classes by simply
declaring an interface that contains variables that are initialized to the desired values.
https://www.youtube.com/watch?v=7w9COsroiyQ&list=PLqleLpAMfxGCtBX7KX
CSir6PnzRBukNmd&index=2 – Link for Interface
25