Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
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
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();
}
} 