What is the result of the following code snippet?
class Parent {
private int x = 10;
}
class Child extends Parent {
int x = 20;
void display() {
System.out.println(super.x + " " + x);
}
}
public class Main {
public static void main(String[] args) {
Child obj = new Child();
obj.display();
}
}
private int x = 10;
}
class Child extends Parent {
int x = 20;
void display() {
System.out.println(super.x + " " + x);
}
}
public class Main {
public static void main(String[] args) {
Child obj = new Child();
obj.display();
}
}
A. 20 10
B. 10 20
C. Runtime exception
D. None of These
Answer: Option B
Solution (By Examveda Team)
The given code snippet involves inheritance in Java. It defines two classes:Parent and Child. The Child class extends the Parent class, which means it inherits its fields and methods.Inside the
Parent class, there is a private integer variable x with a value of 10. In the Child class, there is another integer variable x with a value of 20. Additionally, the Child class has a display() method that prints the values of super.x and x.In Java, when you access a variable with the
super keyword, it refers to the variable of the superclass. When you access a variable without super, it refers to the variable of the current class.Now, let's analyze what happens in the
display() method:-
super.x refers to the x variable in the Parent class, which is 10.-
x refers to the x variable in the Child class, which is 20.So, the
display() method will print "10 20" because it first accesses the x variable of the superclass (Parent) using super.x and then accesses the x variable of the current class (Child) directly.Therefore, the correct answer is:
Option B: 10 20
Join The Discussion
Comments (1)
A. The process of acquiring properties and behaviors of one class by another
B. The process of creating objects
C. The process of encapsulation
D. The process of overloading methods
In Java, which keyword is used to implement inheritance between classes?
A. inheritsFrom
B. inherits
C. implements
D. extends
A. The class that inherits properties and behaviors
B. The child class
C. The class that is inherited from
D. The class that is marked as "final"
In Java, can a subclass inherit constructors from its superclass?
A. Only if the subclass is marked as "final"
B. Yes, a subclass inherits constructors from its superclass
C. Only if the superclass is marked as "static"
D. None of the above

compile time error. x in super class is private