Inheritance

Inheritance allows a new class to extend an existing class. The new class inherits the members of the class it extends. The extended class is allow to use any method contained in the none extended class. In a more general explanation, we have two classes, one is call parent class and the other one is call child class. The child class is allow to use anything that the parent class has like its own and the parent class does not allow to use anything from the child class. Lets see a simple example.

Here is the parent class

/*
    A parent class that holds name and age

*
*/

public class Name_Age
{
    static String name;
    static int age;

  
 // Assign newname to name

    public static void setName(String newname)
    {
        name = newname;
    }

  
 // Assign newage to age

    public static void setAge(int newage)
    {
        age = newage;
    }

    // Returns the name

    public static String getName()
    {
        return name;
    }

   
// Returns the age

    public static int getAge()
    {
        return age;
    }
}
 

Here is the child class that extends the parent class

/*
    This is the child class extends the Name_Age class

*
*/


import java.util.*;

public class Name_AgeDemo extends Name_Age
{
    public static void main(String[] args)
    {
        Scanner key = new Scanner(System.in);

       
// Gets the name from the user

        System.out.print("Enter your name: ");
        String names = key.nextLine();

      
 // Pass the name into setName method

        setName(names);

       
// Gets the age from the user

        System.out.print("Enter your age: ");
        int ages = key.nextInt();

      
 // Pass the age into setAge method

        setAge(ages);

       
// Prints out the name and age

        System.out.println(getName() + " is " + getAge() + " years old");
    }
}

ClickHere to download Thefirstclass.java 

ClickHere to download Thesecondclass.java 

Notice, this is similar to the previous chapter, creating two classes and be able to use methods from other class. So the first class we created is call the parent class and the second class that we created is call the child class. The child class extends the parent class, basically by extending the parent class the child class can use any methods from the parent's class as if they were its own methods. That is the beauty of inheritance.

Note: Parent class could not access any method from the child class.

 

  <Java 24><Home>