Java-Simple Inheritance

Simple Inheritance

Reusability is yet another aspect of object oriented programming. It is always nice if we could reuse something that already exists rather than creating the same all over again. Java supports this concept. Java classes can be reused in several ways. This is basically done by creating new classes, reusing the properties of existing ones. The mechanism of deriving a new class from an old one is called inheritance. The old class is known as the base class or super class or parent class and the new one is called the subclass or derived class or child class. The inheritance allows subclasses to inherit all the variables and methods of their parent classes.

Defining a Subclass

The keyword extends signifies that the properties of the NewData are extended to the Data. The subclass will now contain its own variables and methods as well those of the superclass. This kind of situation occurs when we want to add some more properties to an existing class without actually modifying it.


Program Source

class Data {
    int data1;
    int data2;

class NewData extends Data {
    int data3;
    int data4;

public class Javaapp {

    public static void main(String[] args) {
        NewData da = new NewData();
        da.data1 = 20;
        da.data2 = 40;
        da.data3 = 60;
        da.data4 = 80;
        System.out.println("da.data1 = "+da.data1);
        System.out.println("da.data2 = "+da.data2);
        System.out.println("da.data3 = "+da.data3);
        System.out.println("da.data4 = "+da.data4);

Leave a Comment