The extends Keyword in Java

Java 8Object Oriented ProgrammingProgramming

An object can acquire the properties and behaviour of another object using Inheritance. In Java, the extends keyword is used to indicate that a new class is derived from the base class using inheritance. So basically, extends keyword is used to extend the functionality of the class.

A program that demonstrates the extends keyword in Java is given as follows:

Example

 Live Demo

class A {
   int a = 9;
}
class B extends A {
   int b = 4;
}
public class Demo {
   public static void main(String args[]) {
      B obj = new B();
      System.out.println("Value of a is: " + obj.a);
      System.out.println("Value of b is: " + obj.b);
   }
}

Output

Value of a is: 9
Value of b is: 4

Now let us understand the above program.

The class A contains a data member a. The class B uses the extends keyword to derive from class A. It also contains a data member b. A code snippet which demonstrates this is as follows:

class A {
   int a = 9;
}
class B extends A {
   int b = 4;
}

In the main() method in class Demo, an object obj of class B is created. Then the values of a and b are printed. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String args[]) {
      B obj = new B();
      System.out.println("Value of a is: " + obj.a);
      System.out.println("Value of b is: " + obj.b);
   }
}
raja
Published on 19-Feb-2019 11:17:56
Advertisements