Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

EWIT OOJmodule3pdf

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an existing
class.

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Output:

barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:

weeping...
barking...
eating...
Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Using super

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


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

super is used 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.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
black

white

Creating a Multilevel Hierarchy

Inheritance involves an object acquiring the properties and behaviour of another object. So
basically, using inheritance can extend the functionality of the class by creating a new class that
builds on the previous class by inheriting it.

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:

Example
class A {

void funcA() {

System.out.println("This is class A");

class B extends A {

void funcB() {

System.out.println("This is class B");

class C extends B {

void funcC() {

System.out.println("This is class C");

}
}

public class Demo {

public static void main(String args[]) {

C obj = new C();

obj.funcA();

obj.funcB();

obj.funcC();

Output
This is class A
This is class B
This is class C

When constructors are executed

When a class hierarchy is created, 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 oeder is the same whether or not super() is used. If super() is not used,
then the default or parameterless constructor of each superclass will be executed.

Class A{

A(){

System.out.println(“inside A’s constructor.”);

Class B extends A{

B(){

System.out.println(“inside B’s contructor.”);

Class C extends B{
C(){

System.out.println(“inside C’s constructor.”);

Class CallingCons{

Public static void main(String[] args){

C c=new C();

Method overriding

If 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.

Class A{

Int i,j;

A(int a, int b){

i=a;

j=b;

void show()

system.out.println(“i and j:” + i+ ” “ +j);

Class B extends A{

Int k;

B(int a, int b, int c){


super(a,b);

k=c;

void show(){

system.out.println(“k: “ +k);

class override{

Public static void main(String[] args){

B subob = new B(1, 2, 3);

subob.show();

When show() is invoked on an object of type B, the version of show() defined within B is
used.that is, the version of show() inside B overrides the version declared in A.

Dynamic method Dispatch

Dynamic method dispatch is the mechanism by which a call to an overridden method is


resolved at run time, rather than compile time.

class A

void m1()

System.out.println("Inside A's m1 method");

class B extends A
{

// overriding m1()

void m1()

System.out.println("Inside B's m1 method");

class C extends A

// overriding m1()

void m1()

System.out.println("Inside C's m1 method");

// Driver class

class Dispatch

public static void main(String args[])

// object of type A

A a = new A();

// object of type B

B b = new B();

// object of type C
C c = new C();

// obtain a reference of type A

A ref;

// ref refers to an A object

ref = a;

// calling A's version of m1()

ref.m1();

// now ref refers to a B object

ref = b;

// calling B's version of m1()

ref.m1();

// now ref refers to a C object

ref = c;

// calling C's version of m1()

ref.m1();

Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method

Abstract class in Java

Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

In this example, Shape is the abstract class, and its implementation is provided by the Rectangle
and Circle classes.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.

abstract class Shape{


abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape
() method
s.draw();
}
}

output
drawing circle

final keyword with inheritance in java

 The final keyword is final that is we cannot change.


 We can use final keywords for variables, methods, and class.
 If we use the final keyword for the inheritance that is if we declare any method with
the final keyword in the base class so the implementation of the final method will be the
same as in derived class.
 We can declare the final method in any subclass for which we want that if any other
class extends this subclass.
Case 1: Declare final variable with inheritance
// Declaring Parent class

class Parent {

/* Creation of final variable pa of string type i.e

the value of this variable is fixed throughout all

the derived classes or not overidden*/

final String pa = "Hello , We are in parent class variable";

// Declaring Child class by extending Parent class

class Child extends Parent {

/* Creation of variable ch of string type i.e

the value of this variable is not fixed throughout all

the derived classes or overidden*/

String ch = "Hello , We are in child class variable";

class Test {

public static void main(String[] args) {

// Creation of Parent class object

Parent p = new Parent();

// Calling a variable pa by parent object

System.out.println(p.pa);

// Creation of Child class object

Child c = new Child();

// Calling a variable ch by Child object

System.out.println(c.ch);

// Calling a variable pa by Child object

System.out.println(c.pa);
}

Output

D:\Programs>javac Test.java

D:\Programs>java Test

Hello , We are in parent class variable

Hello , We are in child class variable

Hello , We are in parent class variable

Case 2: Declare final methods with inheritance


// Declaring Parent class

class Parent {

/* Creation of final method parent of void type i.e

the implementation of this method is fixed throughout

all the derived classes or not overidden*/

final void parent() {

System.out.println("Hello , we are in parent method");

// Declaring Child class by extending Parent class

class Child extends Parent {

/* Creation of final method child of void type i.e

the implementation of this method is not fixed throughout

all the derived classes or not overidden*/

void child() {

System.out.println("Hello , we are in child method");

}
}

class Test {

public static void main(String[] args) {

// Creation of Parent class object

Parent p = new Parent();

// Calling a method parent() by parent object

p.parent();

// Creation of Child class object

Child c = new Child();

// Calling a method child() by Child class object

c.child();

// Calling a method parent() by child object

c.parent();

Output

D:\Programs>javac Test.java

D:\Programs>java Test

Hello , we are in parent method

Hello , we are in child method

Hello , we are in parent method

Object class

Object class is present in java.lang package. Every class in Java is directly or indirectly
derived from the Object class. If a class does not extend any other class then it is a direct child
class of Object and if extends another class then it is indirectly derived. Therefore the Object
class methods are available to all Java classes

The Object class provides multiple methods which are as follows:


 tostring() method
 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.
hashCode() method
It returns a hash value that is used to search objects in a collection

getClass() method
It returns the class object of “this” object and is used to get the actual runtime class of the
object.
equals(Object obj) method
It compares the given object to “this” object (the object on which the method is called). It gives
a generic way to compare objects for equality
clone() method
It returns a new object that is exactly the same as this object. For clone() method refer Clone().

Interface

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.

Why use Java interface?


o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must implement all the methods
declared in the interface.

Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
Java Interface Example: Drawable

In this example, the Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used by
someone else. The implementation part is hidden by the user who uses the interface.

//Interface declaration: by first user


interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}}

Output:

drawing circle

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.
// A simple program to Test Interface default

// methods in java

interface TestInterface

// abstract method

public void square(int a);

// default method

default void show()

System.out.println("Default Method Executed");

class TestClass implements TestInterface

// implementation of square abstract method

public void square(int a)

System.out.println(a*a);

public static void main(String args[])

TestClass d = new TestClass();

d.square(4);
// default method executed

d.show();

Output:

16

Default Method Executed

The default methods were introduced to provide backward compatibility so that existing interfaces can
use the lambda expressions without implementing the methods in the implementation class. Default
methods are also known as defender methods or virtual extension methods.

Static Methods:
The interfaces can have static methods as well which is similar to static method of classes.

// A simple Java program to TestClassnstrate static

// methods in java

interface TestInterface

// abstract method

public void square (int a);

// static method

static void show()

System.out.println("Static Metho Executed");

}
class TestClass implements TestInterface

// Implementation of square abstract method

public void square (int a)

System.out.println(a*a);

public static void main(String args[])

TestClass d = new TestClass();

d.square(4);

// Static method executed

TestInterface.show();

Output:
16
Static Method Executed

Private Interface Methods Example


interface Sayable{
default void say() {
saySomething();
}
// Private method inside interface
private void saySomething() {
System.out.println("Hello... I'm private method");
}
}
public class PrivateInterface implements Sayable {
public static void main(String[] args) {
Sayable s = new PrivateInterface();
s.say();
}
}

Output:

Hello... I'm private method

Such like, we can also create private static methods inside an interface.

You might also like