You are on page 1of 13

1 Module -3:BCS306A 2 Module -3:BCS306A

class TestInheritance
{
INHERITANCE
public static void main(String args[])
1. INHERITANCE BASICS {
➢ Inheritance in Java is a mechanism in which one object acquires all the properties and
Dog d=new Dog();
behaviours of a parent object.
d.bark();
➢ Inheritance is an important pillar of OOP (Object-Oriented Programming). It is the
d.eat();
mechanism in Java by which one class is allowed to inherit the features (fields and
}
methods) of another class.
}
➢ Inheritance represents the IS-A relationship, also known as parent-child relationship.
➢ In Java, Inheritance means creating new classes based on existing ones. 1.1 Member Access and Inheritance
➢ A class that inherits from another class can reuse the methods and fields of that class. Although a subclass includes all of the members of its superclass, it cannot access those
➢ In addition, you can add new fields and methods to your current class as well. members of the superclass that have been declared as private.

Example:
The extends keyword is used for inheritance in Java. Using the extends keyword
indicates you are derived from an existing class. In other words, “extends” refers to /* In a class hierarchy, private members remain private to their class. This program contains an
increased functionality.
error and will not compile. */

Syntax : class A

class derived-class extends base-class {


{
int i; // public by default
//methods and fields
} private int j; //Private to A
Example:
void setij(int x, int y)
class Animal{
{
void eat()
{ i = x;
System.out.println("eating...");}
j = y;
}
class Dog extends Animal }
{ }
void bark(){System.out.println("barking...");
class B extends A
}
} {

RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
3 Module -3:BCS306A 4 Module -3:BCS306A

int total; void callMe()


{
void sum()
System.out.print("Hi ");
{ }

total = i + j; //A's j is not accessible here }


class Reference
}
{
} public static void main(String args[])
{
class SimpleInheritance2
A ref;
{
B b = new B();
public static void main(String args[]) ref = b;
ref.callMe();
{
}
B subOb = new B(); }

subOb.setij(10, 12); Output: Hi

subOb.sum();
2. USING SUPER
System.out.println("Total is " + subOb.total); ➢ Whenever the derived class inherits the base class features, there is a possibility that
base class features are similar to derived class features and JVM gets an ambiguity.
}}
➢ To overcome this, super is used to refer super class properties.
1.2 A super class variable can reference a subclass object: ➢ The super keyword in java is a reference variable that is used to refer parent class.
A reference variable of a super class can be assigned a reference to any subclass derived ➢ The keyword “super” came into the picture with the concept of Inheritance. It is majorly
from that super class. used in the following contexts:
Ex:
– super is used to refer immediate parent class instance variable.
class A
{ super.parent_instance_variable_name;

void callMe() – super is used to invoke immediate parent class method


{
super.parent_class_method_name();
System.out.print("Hello");
} – super is used to invoke immediate parent class constructor.
}
super(arglist); // parameterized constructor
class B extends A
{ super(); //default

RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
5 Module -3:BCS306A 6 Module -3:BCS306A

Usage 1. - Using super to refer super class property Usage 2. - super is used to invoke immediate parent class method

class Vehicle class Student

{ {

int speed=50; void message()

} {

class Bike extends Vehicle System.out.println("Good Morning Sir");

{ }

int speed=100; }

void display() class Faculty extends Student

{ {

System.out.println("Vehicle Speed:"+super.speed);//will print speed of vehicle void message()

System.out.println("Bike Speed:"+speed);//will print speed of bike {

} System.out.println("Good Morning Students");

} }

class SuperVarible void display()

{ {

public static void main(String args[]) message();//will invoke or call current class message() method

{ super.message();//will invoke or call parent class message() method

Bike b=new Bike(); }

b.display(); }

} class SuperClassMethod

} {

public static void main(String args[])

RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
7 Module -3:BCS306A 8 Module -3:BCS306A

Faculty f=new Faculty(); Bike b=new Bike();

f.display(); }

} }

} Output:

Usage 3. - super is used to invoke immediate parent class constructor Vehicle is created

class Vehicle Bike is created

{ 3. CREATING A MULTILEVEL HIERARCHY


Vehicle( ) Multilevel inheritance is when a class inherits a class which inherits another class. An
example of this is class C inherits class B and class B in turn inherits class A.
{ A program that demonstrates a multilevel inheritance hierarchy in Java is given as follows:
System.out.println("Vehicle is created"); class A {
void funcA() {
}
System.out.println("This is class A");
}
}
class Bike extends Vehicle }
{ class B extends A {
void funcB() {
Bike()
System.out.println("This is class B");
{
}
super( );//will invoke parent class constructor }
System.out.println("Bike is created"); class C extends B {
void funcC() {
}
System.out.println("This is class C");
}
}
class SuperClassConst }

{ public class Demo {


public static void main(String args[]) {
public static void main(String args[])
C obj = new C();
{
obj.funcA();

RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
9 Module -3:BCS306A 10 Module -3:BCS306A

obj.funcB(); B() {
obj.funcC(); System.out.println("Inside B's constructor.");
} }}
} Create another subclass by extending B.
Output class C extends B {
This is class A C()
This is class B {
This is class C System.out.println("Inside C's constructor.");
}}

4. WHEN CONSTRUCTORS ARE EXECUTED class CallingCons {


public static void main(String args[]) { C c = new C();
A Java program will automatically create a constructor if it is not already defined in the }}
program. It is executed when an instance of the class is created.

For example, Output

Given a subclass called B and a superclass called A, is A’s constructor executed before B’s, Inside A's constructor

or vice versa? Inside B's constructor


Inside C's constructor
The answer is that in a class hierarchy, constructors complete their execution in order of
derivation, from superclass to subclass. Further, since super( ) must be the first statement
executed in a subclass’ constructor, this order is the same whether or not super( ) is used. 5. METHOD OVERRIDING
➢ If subclass (child class) has the same method as declared in the parent class, it is known
If super( ) is not used, then the default or parameter less constructor of each superclass will be
as method overriding in Java.
executed. The following program illustrates when constructors are executed: ➢ 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.
//Demonstrate when constructors are executed.
➢ Method overriding is used to provide the specific implementation of a method which is
Create a super class. already provided by its superclass.
➢ Method overriding is used for runtime polymorphism
class A {
Rules for Java Method Overriding
A() { ➢ The method must have the same name as in the parent class
➢ The method must have the same parameter as in the parent class.
System.out.println("Inside A's constructor."); ➢ There must be an IS-A relationship (inheritance).

}} //Java Program to illustrate the use of Java Method Overriding


//Create a subclass by extending class A. //Creating a parent class.
class B extends A { class Vehicle{

RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
11 Module -3:BCS306A 12 Module -3:BCS306A

//defining a method class B extends A


void run(){System.out.println("Vehicle is running");} {
}
void m1() // overriding m1()
//Creating a child class
class Bike2 extends Vehicle{ {

//defining the same method as in the parent class System.out.println("Inside B's m1 method");
void run(){System.out.println("Bike is running safely");}
}}

class C extends A
public static void main(String args[]){
Bike2 obj = new Bike2(); //creating object {

obj.run();//calling method void m1() // overriding m1()


}
{
}
System.out.println("Inside C's m1 method");
Output:
Bike is running safely }}

6. DYNAMIC METHOD DISPATCH class Dispatch // Driver class

Dynamic Method Dispatch in Java is the process by which a call to an overridden method is {
resolved at runtime (during the code execution). The concept of method overriding is the way
public static void main(String args[])
to attain runtime polymorphism in Java.
{
// A Java program to illustrate Dynamic Method
A a = new A(); // object of type A
// Dispatch using hierarchical inheritance
B b = new B(); // object of type B
class A
C c = new C(); // object of type C
{
A ref; // obtain a reference of type A
void m1()
ref = a; // ref refers to an A object
{
ref.m1(); // calling A's version of m1()
System.out.println("Inside A's m1 method");
ref = b; // now ref refers to a B object
}}
ref.m1(); // calling B's version of m1()

RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
13 Module -3:BCS306A 14 Module -3:BCS306A

ref = c; // now ref refers to a C object // A Simple demonstration of abstract.

ref.m1(); // calling C's version of m1() abstract class A


{
} }
abstract void callme();
Output: // concrete methods are still allowed in abstract classes
Inside A's m1 method void callmetoo() {
System.out.println("This is a concrete method.");
Inside B's m1 method
}
Inside C's m1 method
}
Advantages of Dynamic Method Dispatch class B extends A
➢ Dynamic method dispatch allow Java to support overriding of methods which is central {
for run-time polymorphism. void callme()
➢ It allows a class to specify methods that will be common to all of its derivatives, while {
allowing subclasses to define the specific implementation of some or all of those System.out.println("B's implementation of callme.");
methods.
}
➢ It also allow subclasses to add its specific methods subclasses to define the specific
}
implementation of some.
class AbstractDemo
{
USING ABSTRACT CLASSES public static void main(String args[])
• An abstract class is a class that contains one or more abstract methods. {
• An abstract method is a method without method body. B b = new B();
Syntax: b.callme();
abstract return_type method_name(parameter_list); b.callmetoo();
• An abstract class can contain instance variables, constructors, concrete methods in addition }
to abstract methods.
}
• All the abstract methods of abstract class should be implemented in its sub classes.
USING FINAL WITH INHERITANCE
• If any abstract method is not implemented in its subclasses, then that sub class must be
declared as abstract. final is a keyword in java used for restricting some functionalities. We can declare variables,
methods, and classes with the final keyword.
• We cannot create an object to abstract class, but we can create reference of abstract class.
• Also, you cannot declare abstract constructors or abstract static methods.
➢ During inheritance, we must declare methods with the final keyword for which we are
Java program to illustrate abstract class.
required to follow the same implementation throughout all the derived classes.

RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
15 Module -3:BCS306A 16 Module -3:BCS306A

➢ Note that it is not necessary to declare final methods in the initial stage of inheritance Output
(base class always).
Error
➢ We can declare a final method in any subclass for which we want that if any other class
extends this subclass, then it must follow the same implementation of the method as in Use 3: To prevent inheritance
that subclass.
final class Vehicle
Uses of Final:
{
Final can be used in three ways:
void run()
• To prevent modifications to the instance variable
{
• To Prevent method overriding
System.out.println("running");
• To prevent inheritance
}}
Use 2: To prevent method overriding
class Bike extends Vehicle
class Vehicle
{
{
void run()
final void run()
{
{
System.out.println("running safely with 100kmph");
System.out.println("running");
}}
}}
class FinalClass
class Bike extends Vehicle
{
{
public static void main(String args[])
void run()
{
{
Bike b= new Bike();
System.out.println("running safely with 100kmph");
b.run();
}}
}
class FinalMethod
}
{
Output:
public static void main(String args[])
Class Bike extends vehicle
{
Bike b= new Bike();
b.run();
}
}

RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
17 Module -3:BCS306A 18 Module -3:BCS306A

LOCAL VARIABLE TYPE INFERENCE AND INHERITANC protected Object clone() throws creates and returns the exact copy (clone) of this
Local variable type inference is a feature in Java 10 that allows the developer to skip the type CloneNotSupportedException object.

declaration associated with local variables (those defined inside method definitions, public String toString() returns the string representation of this object.
initialization blocks, for-loops, and other blocks like if-else), and the type is inferred by the
public final void notify() wakes up single thread, waiting on this object's
JDK. monitor.

The following was the only correct syntax: public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.
Class_name variable_name=new Class_name(arguments);
public final void wait(long timeout)throws causes the current thread to wait for the specified
// Sample Java local variable declaration InterruptedException milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).
import java.util.ArrayList;
import java.util.List; public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread
class A { notifies (invokes notify() or notifyAll() method).
public static void main(String a[])
public final void wait()throws causes the current thread to wait, until another thread
{ InterruptedException notifies (invokes notify() or notifyAll() method).
List<Map> data = new ArrayList<>();
protected void finalize()throws Throwable is invoked by the garbage collector before object is
} being garbage collected.
}

THE OBJECT CLASS.


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

Method Description

public final Class getClass() returns the Class class object of this object. The
Class class can further be used to get the metadata of
this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
19 Module -3:BCS306A 20 Module -3:BCS306A

INTERFACES: Example 1: Write a java program to implement interface.

interface Moveable

1. INTERFACES {
➢ The interface in Java is a mechanism to achieve abstraction.
➢ There can be only abstract methods in the Java interface, not the method body. It is int AVG_SPEED=30;
used to achieve abstraction and multiple inheritances in Java using Interface. void Move();
➢ In other words, you can say that interfaces can have abstract methods and variables. It
}
cannot have a method body.
➢ Java Interface also represents the IS-A relationship. class Move implements Moveable

Syntax for Java Interfaces {


interface {
void Move(){
// declare constant fields
System .out. println ("Average speed is: "+AVG_SPEED );
// declare methods that abstract
// by default. }

} }
Implementing Interfaces:
class Vehicle
• Once an interface has been defined, one or more classes can implement that interface.
{
• To implement an interface, include the implements clause in a class definition, and then create
public static void main (String[] arg)
the methods defined by the interface.
{
• The general form of a class that includes the implements clause looks like this:
Move m = new Move();
class classname [extends superclass] [implements interface1 [,interface2...]]
m.Move();
{
}
// class-body
}
}
Example 2: Write a java program to implement interface.
• If a class implements more than one interface, the interfaces are separated with a comma.
interface Teacher
• The methods that implement an interface must be public. Also, the type signature of
{
Implementing method must match exactly the type signature specified in interface definition
void display1();

RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
21 Module -3:BCS306A 22 Module -3:BCS306A

} }

interface Student

{ Accessing implementations through interface references:

void display2(); We 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
class College implements Teacher, Student 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 which calls methods on them.
public void display1()
Ex:
{
interface Test {
System.out.println("Hi I am Teacher");
void call();
}
}
public void display2()
class InterfaceTest implements Test {
{
public void call()
System.out.println("Hi I am Student");
{
}
System.out.println("call method called");
}
}
class CollegeData
}
{
public class IntefaceReferences {
public static void main(String arh[])
public static void main(String[] args)
{
{
College c=new College();
Test f ;
c.display1();
InterfaceTest it= new InterfaceTest();
c.display2();
f=it;
}
f.call();

RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
23 Module -3:BCS306A 24 Module -3:BCS306A

}} Interfaces can be extended:

Variables in Interfaces: One interface can inherit another by use of the keyword extends.

We can use interfaces to import shared constants into multiple classes by simply declaring an The syntax is the same as for inheriting classes. When a class implements an interface that
interface that contains variables that are initialized to the desired values. inherits another interface, it must provide implementations for all methods defined within the
interface inheritance chain.
When we include that interface in a class (that is, when you “implement” the interface), all of
those variable names will be in scope as constants. DEFAULT INTERFACE METHODS
If an interface contains no methods, then any class that includes such an interface doesn’t Default methods enable you to add new functionality to the interfaces of your libraries and
actually implement anything. Itis as if that class were importing the constant fields into the ensure binary compatibility with code written for older versions of those interfaces.
class name space as final variables.
If we have an implemented method inside an interface with default keyword, then we will call
Example: Java program to demonstrate variables in interface. it as a Default method. We also call it defender method or virtual extension method.

interface left Use static Methods in an Interface, Private Interface Methods.

{ interface Human {

int i=10; void speaks();


void eats();
}
default void walks(){
interface right
System.out.println("Every human follows the same walking pattern");
{ }

int i=100; }
Implementing classes are free to provide their own implementation of the default method. If
}
the implementing class doesn’t override the default method, it means that the class doesn’t
need that functionality in it.
class Test implements left,right
PRIVATE INTERFACE METHODS
{
➢ We can create private methods inside an interface. Interface allows us to declare private
public static void main(String args[]) methods that help to share common code between non-abstract methods.
{
// private methods in interfaces
System.out.println(left.i);//10 will be printed
interface Sayable{
System.out.println(right.i);//100 will be printed*/
default void say() {
}}
saySomething();

RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
25 Module -3:BCS306A 26 Module -3:BCS306A

}
6) An abstract class can extend An interface can extend another Java interface only.
another Java class and implement
// Private method inside interface multiple Java interfaces.
private void saySomething() { 7) An abstract class can be extended An interface can be implemented using keyword
using keyword "extends". "implements".
System.out.println("Hello... I'm private method");
8) A Java abstract class can have Members of a Java interface are public by default.
} class members like private, protected,
etc.
}
9)Example: Example:
public class PrivateInterface implements Sayable { public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
public static void main(String[] args) { } }

Sayable s = new PrivateInterface();

s.say();

}}

Output:

Hello... I'm private method

Difference Between Abstract class and interface

Abstract class Interface

1) Abstract class can have abstract Interface can have only abstract methods. Since Java
and non-abstract methods. 8, it can have default and static methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static
variables.

4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

5) The abstract keyword is used to The interface keyword is used to declare interface.
declare abstract class.

RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE

You might also like