In Java programming, a class can inherit properties and methods from another class, which is known as the parent or super class. The class that inherits the properties and methods is called a child or sub class. This is known as inheritance.
The child class can access all the public and protected members of the parent class. However, the private members of the parent class cannot be accessed by the child class.
public class Parent { public void printParent() { System.out.println("This is the parent class."); } } public class Child extends Parent { public void printChild() { System.out.println("This is the child class."); } } public class Main { public static void main(String[] args) { Child child = new Child(); child.printParent(); child.printChild(); } }
In the above example, the child class (Child) inherits from the parent class (Parent) using the keyword "extends." As a result, the child class has access to the public member "printParent()". The child class also has its own method "printChild()". The Main class creates an object of the child class and calls both methods.
When the program is executed, the following output is produced:
This is the parent class. This is the child class.
This demonstrates how a child class can inherit from a parent class in Java.