Java: inheritance and constructors

When an object is created from an inherited class, the constructor of the superclass is performed before the constructor of the subclass. That is, when an object is created from an inherited class, the implicit constructor of the superclass is performed. In the case of overloading, if you want to call a constructor other than the implicit constructor, make an explicit call using super, the reserved word.

Implicit constructors are constructors that have no parameters. The sentence using super must be on the first line.

class A1 {
	double d1;
	A1() {
		System.out.println("Class A1 performs this constructor");
		d1 = 10 * 10;
	}
}

class A2 extends A1 {
	double d2;
	A2() {
		System.out.println("Perform a constructor for class A2");
		d2 = 10 * 10 * 10;
	}
}

class A3 extends A2 {
	double d3;
	A3() {
		System.out.println("Perform a constructor for class A3");
		d3 = 10 * 10 * 10 * 10;
	}
}

class Constructors1 {
	public static void main(String args[]) {
		A3 super1 = new A3();
		System.out.println("2 to the power of 10: " + super1.d1);
		System.out.println("3 to the power of 10: " + super1.d2);
		System.out.println("4 to the power of 10: " + super1.d3);
	}
}
Creating an object of an inherited class Example 1
class A1 {
	int d1;
	int s;
	A1(int S1) {
		System.out.println("Perform a constructor for class A1");
		s = s1;
		d1 = s * s;
	}
}

class A2 extends A1 {
	int d2;
	int t;
	A2(int s1, int t1) {
		super(s1); //Explicitly calling the constructor of the superclass
		System.out.println("Perform a constructor for class A2");
		t = t1;
		d2 = t * t;
	}
}

class Constructors2 {
	public static void main(String args[]) {
		A2 super2 = new A2(10, 20);
		System.out.println("The square of 10: " + super2.d1);
		System.out.println("The square of 20: " + super2.d2);
	}
}
Creating an object of an inherited class Example 2

Share This Post

댓글 남기기

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

Latest Post