+ 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"

15th Jun 2019, 7:02 PM
stephen haokip
stephen haokip - avatar
3 Answers
+ 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
16th Jun 2019, 6:58 AM
zemiak
+ 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
15th Jun 2019, 7:07 PM
Airree
Airree - avatar
+ 2
stephen haokip change this line public int x = 42; to protected int x = 42;
15th Jun 2019, 11:15 PM
Dlite
Dlite - avatar