Deriving a Class in Java


A class can be derived from the base class in Java by using the extends keyword. This keyword is basically used to indicate that a new class is derived from the base class using inheritance. It can also be said that it is used to extend the functionality of the class.

A program that demonstrates this is given as follows:

Example

 Live Demo

class A {
   void funcA() {
      System.out.println("This is class A");
   }
}
class B extends A {
   void funcB() {
      System.out.println("This is class B");
   }
}
public class Demo {
   public static void main(String args[]) {
      B obj = new B();
      obj.funcA();
      obj.funcB();
   }
}

Output

This is class A
This is class B

Now let us understand the above program.

The class A contains a member function funcA(). The class B uses the extends keyword to derive from class A. It also contains a member function funcB(). A code snippet which demonstrates this is as follows:

class A {
   void funcA() {
      System.out.println("This is class A");
   }
}
class B extends A {
   void funcB() {
      System.out.println("This is class B");
   }
}

In the main() method in class Demo, an object obj of class B is created. Then the functions funcA() and funcB() are called. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String args[]) {
      B obj = new B();
      obj.funcA();
      obj.funcB();
   }
}

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements