Website For Developers

Inheritance in Java



Syntax of child class

class child_class_name extends parent_class_name {
//body of the child class
}

To extend a class, extends keyword is used in the class declaration.
extends position: after the child/derived class and before the parent/base class.


Inheritance in Java Example#1

//parent class
class Parent {
   String parentString = "Hey! Im Parent class String.";
}

//child class
class Child extends Parent {
   String childString = "Hey! This is a child class string.";

   public static void main (String [] args) {
     Child object = new Child();
     System.out.println(object.childString);
     System.out.println(object.parentString);
   }
}

Output

Hey! This is a child class string.
Hey! Im Parent class String.


Inheritance in Java Example#2

class Person {
   int ssn,age;
   Scanner scan = new Scanner(System.in);
   void personInfo() {
     System.out.println( "Enter your SSN number:" );
     ssn = scan.nextInt();
     System.out.println("Enter your age:" .);
     age = scan.nextInt();
   }
}

class Employee extends Person {
   Scanner scan = new Scanner(System.in);
   int salary, hours;
   void employeeInfo() {
     System.out.println( "Enter your salary:" );
     salary = scan.nextInt();
     System.out.println( "Enter your weekly work hours:" );
     hours = scan.nextInt();
   }

   public static void main (String [] args) {
     Employee object = new Employee ();

     object.personInfo();
     object.employeeInfo();
   }
}

Output

Enter your SSN number:
230983
Enter your age:
39
Enter your salary:
5000
Enter your weekly work hours:
40



Multilevel Inheritance in Java

Syntax

class GrandFather {
// body
}

class Father extends GrandFather {
// body
}

class Son extends Father {
// body
}