+ 1
Hey guys... i dont know how this works
// Created by SoloLearn // Language: Java // Task Description: Fix the errors to print "The result is: 42". class A { public A() { System.out.print("The result is: "); } public int x = 42; } class B extends A { public B() { System.out.print(x); } } class Program { public static void main(String[] args) { B obj = new B(); } } Why is the output "the result is 42"
3 Respuestas
+ 2
you can imagine it like
public B() {
super();
System.out.print(x);
}
super() call super class constructor, if omitted, it is added automatically
A prints:
"The result is: "
B prints: 42
B can see variable x because inherited members from A
+ 4
B is a subclass of A, so when you make a new object with B, before B, A's constructor is called, because it's its super class
+ 2
stephen haokip change this line
public int x = 42;
to
protected int x = 42;