Module - 3 - Oop With Java
Module - 3 - Oop With Java
Lecture notes
Name Of the Programme B.E -AIML
Scheme 2022
MODULE III
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 the process by which one class acquires the properties (instance variables,
methods) of another class.
• Inheritance creates an IS-A relationship , meaning the child is a more specific version of the
parent.
Super class / Base class/ Parent class
➢ TYPES OF INHERITANCE:
• Single Inheritance.
• Multilevel Inheritance.
• Hierarchical Inheritance.
• Multiple Inheritance
/* single inheritance */
import [Link].*;
class A
{
public int i;
public A()
{
[Link](" \n \t default constructor A() is called");
i=10;
}
public void Adisplay()
{
[Link](" \n \t in A class i= " +i);
}
}
class B extends A
{
public int j;
public B()
{
[Link](" \n \t default constructor B() is called");
j=20;
}
public void Bdisplay()
{
j=i+1;
[Link](" \n \t in B class j= "+j);
}
}
class Simple
{
public static void main(String arr[])
{
[Link](" \n \t start of main()");
B b=new B();
[Link]();
[Link]();
[Link](" \n \t end of main()");
}
}
OUTPUT :
start of main()
default constructor A() is called
default constructor B() is called
in A class i= 10
in B class j= 11
end of main()
}
class C extends B
{
public int k;
public C()
{
[Link](" \n \t constructor C() is called");
k=30;
Prof KALIDASS M, Dept of AIML SSCE, Anekal
cseCSECCSE
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
}
public void Cdisplay()
{
k=i+j;
[Link](" \n \t in C class k= "+k);
}
}
class MulLevel
{
public static void main(String arr[])
{
[Link](" \n \t start of main()");
C c=new C();
[Link]();
[Link]();
[Link]();
[Link](" \n \t end of main()");
}
}
OUTPUT :
start of main()
constructor A() is called
constructor B() is called
constructor C() is called
in A class i= 10
in B class j= 11
in C class k= 21
end of main()
class A
{
A()
{
[Link]("A's constructor.");
}
}
class B extends A
{
B()
{
[Link]("B's constructor.");
}
}
class C extends B
{
C()
{
[Link]("C's constructor.");
}
}
class CallingCons
{
public static void main(String args[])
{
C c = new C();
Output:
A's constructor
B's constructor
C's constructor
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as a method in
its superclass, then the method in the subclass is said to override the method in the superclass. When an
overridden method is called from within a subclass, it will always refer to the version of that method defined
by the subclass. The version of the method defined by the superclass will be hidden.
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
[Link]("k: " + k)
}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
[Link]();
}
Output:
k: 3
class Base
{
void dispB()
{
[Link]("Super class " );
}
}
class Derived extends Base
{
void dispD()
{
[Link]("Sub class ");
}
}
class Demo
{
public static void main(String args[])
{
Base b = new Base();
Derived d=new Derived();
b=d; //superclass reference is holding subclass object
[Link]();
//[Link](); error!!
}
}
➢ SUPER KEYWORD:
• ‘super’ is used when a subclass wants to refer to its immediate superclass members.
• ‘super’ has two general forms.
✓ To make a call to the super class constructor from sub classconstructor.
✓ The second is used to access a member of the superclass that has been hidden
by a member of a subclass i.e To access superclass member (variable or method)
when there is a duplicate member name in the subclass
public int i;
public A()
{
[Link](" \n \t constructor A() is called");
i=10;
}
public void display()
{
[Link](" \n \t in A class i= " +i);
}
}
class B extends A
{
public int i;
public B()
{
super();
[Link](" \n \t constructor B() is called");
this.i=20;
super.i=30; // points the super class instance variable.
}
public void display()
{
[Link](); // calling super class method.
this.i=this.i+super.i;
[Link](" \n \t in B class subofi+supofi = "+this.i);
}
}
class Super
{
public static void main(String arr[])
{
[Link](" \n \t start of main()");
B b=new B();
[Link]();
[Link](" \n \t end of main()");
}
}
OUTPUT :
start of main()
constructor A() is called
constructor B() is called
in A class i= 30
in B class
subofi+supofi = 50end
of main
abstract class A
abstract void
callme();void
callmetoo()
{
[Link]("This is a concrete method.");
class B extends A
{
class AbstractDemo
{
public static void main(String args[])
{
B b = new B(); //subclass object [Link](); //calling abstract
Prof KALIDASS M, Dept of AIML SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
method [Link](); //callingconcretemethod
}
Example: Write an abstract class shape, which has an abstract method area(). Derive three classes
Triangle, Rectangle and Circle from the shape class and to override area(). Implement run-time
polymorphism by creating array of references to supeclass. Compute area of different shapes and display
the same.
Solution:
uct
or
b=x
h=y
double area()
{
//method overriding
[Link]("\nArea of Triangle
is:");return 0.5*b*h;
Circle(int rad)
{
r=rad;
double area()
{
//constructor
//overriding
[Link]("\nArea of Circle
is:");return PI*r*r;
double area()
{
//constructor
//overriding
[Link]("\nArea of Rectangle
is:");return a*b;
}
}
class AbstractDemo
{
public static void main(String args[])
{
for(int i=0;i<3;i++)
[Link](r[i].area());
Output:
Area of Triangle
is:6.0 Area of
Rectangle is:30.0
Area of Circle
is:12.5664
class A
void callme()
[Link]("Inside A");
}
}
class B extends A
{
void callme()
{
[Link]("Inside B");
}
class C extends A
{
void callme()
{
[Link]("Inside C");
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
A r; //Superclass reference
r = a; //holding subclass object
[Link]();r = b;
[Link]();r = c;
[Link]();
METHOD PURPOSE
Object clone() Creates a new object that is same as the object being cloned
int hashCode() Returns the hashcode associated with the invoking object
void wait()
void wait(long
milliseconds) Waits on another thread of execution
void wait(long
milliseconds, int
nanoseconds)
The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may override the
others. Theequals( ) 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
automaticallycalled when an object is output using println( ). Many classes override this method.
Interfaces
Interface is an abstract type that can contain only the declarations of methods and constants. Interfaces are
syntactically like classes, but they do not contain instance variables, and their methods are declared
without any body. Any number of classes can implement an interface. One class may implement many
interfaces. By providing the interface keyword, Java allows you to fully utilize the “one interface, multiple
methods” aspect of polymorphism. Interfaces are alternative means for multiple inheritance in Java.
Defining an Interface
An interface is defined much like a class. This is the general form of an interface:
• When no access specifier is mentioned for an interface, then it is treated as default and the interface
is only available to other members of the package in which it is declared. When an interface is declared
as public, the interface can be used by any other code.
• All the methods declared are abstract methods and hence are not defined inside interface. But a
class implementing an interface should define all the methods declared inside the interface.
• Variables declared inside of interface are implicitly final and static, meaning they cannot be
changed by the implementing class.
Implementing Interface
To implement an interface, include the implements clause in a class definition, and then create the methods
defined by the interface. The class that implements the interface has to have full definitions of all the abstract
methods in the interface. The general form of a class that includes the implements clause looks like this:
interface it1
{
int x=10, y=20;
public void add(int a, int b);
public void sub(int a, int b);
}
interface X
{
int x = 10;
public void display();
}
interface Y
{
int y = 20;
public void add();
}
class A implements X,Y
{
public void display()
{
[Link]("Class-B Method : x = "+ x + " y = " + y);
}
public void add()
{
[Link]("Class-B Method : x+y = "+ (x+y));
}
}
class InterfaceRef
{
public static void main(String args[])
{
//Reference of X
X objX = new A();
[Link]();
//Reference of Y
Y objY = new A();
[Link]();
}
}
Output:
If a class includes an interface but does not fully implement the methods defined by that interface, then the
class becomes abstract class and must be declared as abstract in the first line of its class definition.
Example:
interface it1
{
int x=10, y=20;
public void add(int a, int b);
public void sub(int a, int b);
}
abstract class It2 implements it1
{
public void add(int s, int w)
{
[Link](“Addition=” + (s+w));
}
}
class It3 extends It2
{
public void sub(int s, int w)
{
[Link] (“Subtraction=” + (s-w));
}
public static void main(String args[])
{
It3 obj=new It2( );
[Link](5,6);
}
}
Note: Interfaces may look like abstract classes. But there are lot of differences between them as shown in
the following table:
One interface can inherit another interface by using the keyword extends. The syntax is the same as for
inheriting classes. When a class implements an interface that inherits another interface, it must provide
implementations for all methods defined within the interface inheritance chain.
interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
class MyClass implements B
{
public void meth1()
{
[Link]("Implement meth1().");
}
public void meth2()
{
[Link]("Implement meth2().");
}
public void meth3()
{
[Link]("Implement meth3().");
}
}
class IFExtend
{
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Default Interface Methods, Use static Methods in an Interface
Important Points:
• Interfaces can have default methods with implementation in Java 8 on later.
• Interfaces can have static methods as well, similar to static methods in classes.
• Default methods were introduced to provide backward compatibility for old interfaces so that they
can have new methods without affecting existing code.
• Default methods are also known as defender methods or virtual extension methods.
Before Java 8, interfaces could have only abstract methods. The implementation of these methods has
to be provided in a separate class. So, if a new method is to be added in an interface, then its
implementation code has to be provided in the class implementing the same interface. To overcome this
issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods
with implementation without affecting the classes that implement the interface. In a typical design based
on abstractions, where an interface has one or multiple implementations, if one or more methods are
added to the interface, all the implementations will be forced to implement them too. Otherwise, the
design will just break down.
Default interface methods are an efficient way to deal with this issue. They allow us to add new methods
Prof KALIDASS M, Dept of AIML SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
to an interface that are automatically available in the implementations. Therefore, we don’t need to
modify the implementing classes.
Like regular interface methods, default methods are implicitly public; there’s no need to specify the public
modifier.
Unlike regular interface methods, we declare them with the default keyword at the beginning of the
method signature, and they provide an implementation.
// A simple program to Test Interface default methods in java
interface TestInterface
{
public void square(int a); // abstract method
default void show() // default method
{
[Link]("Default Method Executed");
}
}
class TestClass implements TestInterface
{
public void square(int a)
{
[Link](a*a);
}
public static void main(String args[])
{
TestClass d = new TestClass();
[Link](4);
[Link]();
}
}
Output:
16
Static Methods:
The interfaces can have static methods as well which is similar to static method of classes.
// A simple Java program to demonstrate static methods in java
interface TestInterface
{
public void square (int a); // abstract method
static void show() // static method
{
[Link]("Static Method Executed");
}
}
class TestClass implements TestInterface
{
public void square (int a)
{
[Link](a*a);
}
public static void main(String args[])
{
TestClass d = new TestClass();
[Link](4);
[Link]();
}
}
Output:
16
[Link]();
// use super keyword to call the show
// method of TestInterface2 interface
[Link]();
}
Default TestInterface1
Default TestInterface2
Private Interface Methods
Rules For using Private Methods in Interfaces
• Private interface method cannot be abstract and no private and abstract modifiers together.
• Private method can be used only inside interface and other static and non-static interface methods.
• Private non-static methods cannot be used inside private static methods.
• We should use private modifier to define these methods and no lesser accessibility than private
modifier.
// Java 9 program to illustrate default, static private methods in interfaces
public interface TempI
{
public abstract void mul(int a, int b);
public default void add(int a, int b)
{
sub(a, b); // private method inside default method
div(a, b); // static method inside other non-static method
Prof KALIDASS M, Dept of AIML SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
[Link](2, 3);
[Link](6, 2);
[Link](5, 3);
}
}
OUTPUT : Answer by Abstract method = 6 // mul(2, 3) = 2*3 = 6
Answer by Private method = 4 // sub(6, 2) = 6-2 = 4
Answer by Private static method = 3 // div(6, 2) = 6/2 = 3
Answer by Default method = 8 // add(6, 2) = 6+2 = 8
Answer by Private static method = 1 // div(5, 3) = 5/3 = 1
Answer by Static method = 2 // mod(5, 3) = 5%3 = 2
Example for abstract method / default method / static method / private method / private static
method
[Link]("private method");
}
private static void method5(){
[Link]("private static method");
}
}
public class CustomClass implements CustomInterface
{
@Override
public void method1()
{
[Link]("abstract method");
}
public static void main(String[] args)
{
CustomInterface instance = new CustomClass();
instance.method1();
instance.method2();
CustomInterface.method3();
}
}
Output:
abstract method
private method
private static method
default method
private static method
static method
Develop a JAVA program to create an interface Resizable with methods resizeWidth(int width) and
resizeHeight(int height) that allow an object to be resized. Create a class Rectangle that implements
the Resizable interface and implements the resize methods.
interface Resizable
{
void resizeWidth(int width);
void resizeHeight(int height);
}
[Link](15);
[Link](30);
Output:
Original Rectangle: Width=10, Height=20
Resized Rectangle: Width=15, Height=30