Inheritance | Java: Inheritance means gets the properties from parent. With this child class can access the variables or methods from parent class.
Syntax: class child_class extends parent_class .
Here is the Code:
- import java.io.*;
- class Main {
- public static void main (String[] args) {
- A a = new A(1);
- B b = new B(3);
- System.out.println(a.getX());
- System.out.println(b.getX());
- }
- }
- class B extends A
- {
- public B(int x)
- {
- super(x);
- }
- }
- class A
- {
- int x;
- A(int x)
- {
- this.x = x;
- }
- public int getX()
- {
- return this.x;
- }
- }
Output:
1
3
Here is the Video: