Inheritance in java

               Inheritance is the process of getting properties from base class to child class. A simple implementation of inheritance is given as follows.

Base class : Fruit

Child class : Apple

Two functions:

shape()

taste()

create a object for child class Apple. Access the two functions using this child class object.

// Parent class

class Fruit {

    void shape() {

        System.out.println("Apple is round");

    }

}

// Child class

class Apple extends Fruit {

    void taste() {

        System.out.println("Apple is sweet");

    }

}

public class sampleinheritance {

    public static void main(String[] args) {

        Apple a1 = new Apple();

        a1.shape();  // Method inherited from Fruit

        a1.taste(); // Method of Apple class

    }

}

Output:

C:\raji\blog>javac sampleinheritance.java

C:\raji\blog>java sampleinheritance

Apple is round

Apple is sweet

Some of the examples of inheritance are given below.

Examples of inheritance:

//Java program to implement inheritance using override

·       Create a base class “Vehicle” with a function Info().

·       Inherit a class Bus from Vehicle. Override the function Info().

·       Create a class “sampleInherit”. Define an object and call the function overridden function.

class Vehicle {

    void Info() {

        System.out.println("This is a vehicle");

    }

}

class Bus extends Vehicle {

    @Override

    void Info() {

        System.out.println("This is a bus");

    }

}

public class sampleInher {

    public static void main(String[] args) {

        Vehicle myBus = new Bus();

        myBus.Info(); 

    }

}

The output is given by,

C:\raji\blog>javac sampleInher.java

C:\raji\blog>java sampleInher

This is a bus

//Java program to implement inheritance using super

 Base class:Vehicle , child class :Car

Member function: Sound(),this function is overridden

class Vehicle {

    void sound() {

        System.out.println("bang");

    }

}

class Car extends Vehicle {

    @Override

    void sound() {

        super.sound();  // Call the superclass method

        System.out.println("Boom");

    }

}

public class Main10 {

    public static void main(String[] args) {

        Car ca = new Car();

        ca.sound();

    }

}

Output:

C:\raji\blog>javac Main10.java

C:\raji\blog>java Main10

bang

Boom

This is the way of implementing inheritance in java.

No comments:

Post a Comment