You are on page 1of 29

INHERITANCE

SCUD COMP
Inheritance in Java is a mechanism in which one object acquires all
the properties and behaviors of a parent object. It is an important
part of OOPs (Object Oriented programming system).
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. Moreover, you can add new methods and fields in your
current class also
Why use inheritance in java
•For Method Overriding (so runtime
polymorphism can be achieved).
•For Code Reusability
Terms used in Inheritance
•Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
•Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
•Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
•Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when
you create a new class. You can use the same fields and methods already
defined in the previous class.
The extends keyword indicates that you are making
a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
Types of inheritance in java
 there can be three types of inheritance in java: single, multilevel and hierarchical. Multiple
inheritance is not allowed in Java. It can be got by using Interface

Class A Class X Class M

Cass B Class y Class N Class O

Hierarchial
Single

Class z

Multilevel
1.class Animal{  
2.void eat(){System.out.println("eating...");}  
3.}  
4.class Dog extends Animal{  
5.void bark(){System.out.println("barking...");}  
6.}  
7.class BabyDog extends Dog{  
8.void weep(){System.out.println("weeping...");}  
9.}  
10.class TestInheritance2{  
11.public static void main(String args[]){  
12.BabyDog d=new BabyDog();  
13.d.weep();  
14.d.bark();  
15.d.eat();  
16.}}  
1.class Animal{  
2.void eat(){System.out.println("eating...");}  
3.}  
4.class Dog extends Animal{  
5.void bark(){System.out.println("barking...");}  
6.}  
7.class Cat extends Animal{  
8.void meow()
{System.out.println("meowing...");}  
9.}  
10.class TestInheritance3{  
11.public static void main(String args[]){  
12.Cat c=new Cat();  
13.c.meow();  
14.c.eat();  
15.//c.bark();//C.T.Error  
16.}}
Why multiple inheritance is not supported in java?

1.class A{  
2.void msg(){System.out.println("Hello");}  
3.}  
4.class B{  
5.void msg(){System.out.println("Welcome");}  
6.}  
7.class C extends A,B{//suppose if it were  
8.   
9. public static void main(String args[]){  
10.   C obj=new C();  
11.   obj.msg();//
Now which msg() method would be invoked?  
12.}  
13.} 
Points to remember:
Every class declared in java is direct or indirect subclass o a
class Object defined in java.lang package. That means even if
you declare a class which is not inheriting from any other ,
class, still your class has a superclass the class Object provided
by java.

Java allows only single inheritance and which means that a


class has at most one immediate superclass.
Every class can have only one immediate superclass…that is
why multiple inheritance is not allowed.
Overriding methods and hiding member variables:
Some times a subclass uses the same names for variables and
methods as in the superclass this will lead to methods being
overridden and variables being hidden

That is if we try to used the method or variable without explicitly


specifying its parent class’s name, only the subclass member
would be used or called.
Int a Int w

Public int b Int j


Class nnm

Private int x Int k


Class demo

Protected int c Int l


Class xyz
The final variables are constants, they cannot be changed. The
final methods cannot be overridden by subclasses. A final
class cannot be extended . Eg String class is final
Abstract Class
A concrete superclass is the one whose objects can be
declared and created. Sometimes, we need to define a
superclass having general characteristics and behavious of its
subclasses, but no object of such class should be defines as
the class depict a concept only.
Eg:
abstract class shape{
String name;
double area;
void display()
{}
}
A class that is declared using “abstract” keyword is known as abstract class.
It can have abstract methods(methods without body) as well as concrete
methods (regular methods with body). A normal class(non-abstract class)
cannot have abstract methods. In this guide we will learn what is a abstract
class, why we use it and what are the rules that we must remember while
working with it in Java.
An abstract class can not be instantiated, which
means you are not allowed to create an object of
it. 
Why we need an abstract class?
Lets say we have a class Animal that has a method sound() and the
subclasses(see inheritance) of it like Dog, Lion, Horse, Cat etc. Since the animal sound
differs from one animal to another, there is no point to implement this method in
parent class. This is because every child class must override this method to give its
own implementation details, like Lion class will say “Roar” in this method and Dog class
will say “Woof”.
So when we know that all the animal child classes will and should override this
method, then there is no point to implement this method in parent class. Thus, making
this method abstract would be the good choice as by making this method abstract we
force all the sub classes to implement this method( otherwise you will get compilation
error), also we need not to give any implementation to this method in parent class.
//abstract parent class
abstract class Animal{ //abstract method
public abstract void sound(); } //Dog class
extends Animal
class Dog extends Animal
{ public void sound()
{ System.out.println("Woof"); }
public static void main(String args[])
{ Animal obj = new Dog();
obj.sound(); } }
class circle extends shape
{
double radius;
double calcarea()
{
return 3.14*radius * radius);
}
Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no
body).  
•Interfaces specify what a class must do and not how. It is the blueprint of
the class.
•An Interface is about capabilities like a Player may be an interface and any
class implementing Player must be able to (or must implement) move(). So
it specifies a set of methods that the class has to implement.
•If a class implements an interface and does not provide method bodies for
all functions specified in the interface, then the class must be declared
abstract.
•A Java library example is, Comparator Interface. If a class implements this
interface, then it can be used to sort a collection.
Why do we use interface ?
•It is used to achieve total abstraction.
•Since java does not support multiple inheritance in case of class, but
by using interface it can achieve multiple inheritance
•Interfaces are used to implement abstraction. So the question arises
why use interfaces when we have abstract classes?

The reason is, abstract classes may contain


non-final variables, whereas variables in
interface are final, public and static.
interface Player
{
final int id = 10;
int move();
//} Java program to demonstrate working of
// interface.
import java.io.*;

// A simple interface
interface In1
{
// public, static and final
final int a = 10;

// public and abstract


void display();
// A class that implements the interface.
class TestClass implements In1
{
// Implementing the capabilities of
// interface.
public void display()
{
System.out.println("Geek");
}

// Driver Code
public static void main (String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}
Output:
10
class Bicycle implements Vehicle{
      
    int speed;
    int gear;
      
     // to change gear
    @Override
    public void changeGear(int newGear){
          
        gear = newGear;
    }
      
    // to increase speed
    @Override
    public void speedUp(int increment){
          
        speed = speed + increment;
    }
// to decrease speed
    @Override
    public void applyBrakes(int decrement){
          
        speed = speed - decrement;
    }
      
    public void printStates() {
         System.out.println("speed: " + speed
              + " gear: " + gear);
    }
}
  

    
class Bike implements Vehicle {
      
    int speed;
    int gear;
      
    // to change gear
    @Override
    public void changeGear(int newGear){
          
        gear = newGear;
    }
 
    // to increase speed
    @Override
    public void speedUp(int increment){
          
        speed = speed + increment;
    }
      
    // to decrease speed
    @Override
    public void applyBrakes(int decrement){
          
        speed = speed - decrement;
    }
      
    public void printStates() {
         System.out.println("speed: " + speed
             + " gear: " + gear);
    }
      
}
class GFG {
      
    public static void main (String[] args) {
      
        // creating an inatance of Bicycle 
        // doing some operations 
        Bicycle bicycle = new Bicycle();
        bicycle.changeGear(2);
        bicycle.speedUp(3);
        bicycle.applyBrakes(1);
          
        System.out.println("Bicycle present state :");
        bicycle.printStates();
          
      
  // creating instance of the bike.
        Bike bike = new Bike();
        bike.changeGear(1);
        bike.speedUp(4);
        bike.applyBrakes(3);
          
        System.out.println("Bike present state :");
        bike.printStates();
    }
}

You might also like