What will be displayed?

class A {
    int x = 1;

    public void printX() {

    public int getX() {
        return x;

class B extends A {
    int x = 2;

    public int getX() {
        return x + 1;

public class Test {
    public static void main(String[] args) {
        A classA = new B();
Method printX() displays the value returned by the method getX(). This brings overlapped method of class B, which returns x+1 and the field value x is also taken from the class B.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Sign Up Now
or Subscribe for future quizzes