Java: Class inheritance and member variable inheritance

The concept of inheritance in Java is a core concept that provides the key features of object-oriented programming: module reuse and code simplicity.

Java uses the concept of inheritance to construct a hierarchy of classes. The hierarchy of this class inherits from the classes provided by the JDK.

In Java, every class has a superclass, and the top class of all classes is the java.lang.Object class.

To specify an ancestor class for inheritance, use the keyword “extends”. Classes with inheritance can be declared as follows:

[public/final/abstract] class ClassName extends ParentClassName {
	...
}
class A {
	int aa = 1;
}

class B extends A {
	int bb = 2;
}

class C extends B {
	int cc = 3;
}

class Dabc {
	public static void main(String args[]) {
		C objc = new C();
		System.out.println("The value of the object attribute variable 'aa' of the objc object is " + objc.aa);
		System.out.println("The value of the object attribute variable 'bb' of the objc object is " + objc.bb);
		System.out.println("The value of the object attribute variable 'cc' of the objc object is " + objc.cc);
	}
}
Java inheritance example 1
class A {
	int i;
	private int j;

	void setij(int x, int y) {
		i = x;
		j = y;
	}
}

class B extends A {
	int total;

	void sum() {
		total = i + j;
		//An error occurred. Subclass can not use variable j of private type
	}
}

class Inheritance1 {
	public static void main(String args[]) {
		B subob = new B();
		subOb.sum();
	}
}
Java inheritance example 2
class B1 {
	int x;
}

class B2 extends B1 {
	String x;
}

class Inheritance2 {
	public static void main(String args[]) {
		B2 b2 = new B2();
		b2.x = "Java that is easy to understand";
		//Int x declared in class B1 is masked
		//If you try to put b2.x = 50, I get an error

		System.out.println("The x value contained in object b2 : " + b2.x);
		B1 b1 = new B1();
		b1.x = 5000;
		System.out.println("The x value contained in object b1 : " + b1.x);

	}
}
Java inheritance example 3
//Class variables can also be inherited
//When a class variable of an ancestor class is defined in a subclass, the variable of the ancestor class is hidden.
class C1 {
	static int x;
	static int y;
}

class C2 extends C1 {
	static String x;
}

class Inheritance3 {
	public static void main(String args[]) {
		C2.x = "Java that is easy to understand";
		//Int x declared in class C1 is masked
		C1.y = 20000;
		C1.x = 30000;

		System.out.println("The value contained in the class variable c2.x : " + c2.x);
		System.out.println("The value contained in the class variable c2.y(inherited from C1): " + c2.y);
		System.out.println("The value contained in the class variable c1.x: " + c1.x);
	}
}
Java inheritance example 4

Share This Post

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다

Latest Post