What will be printed after compiling and running the following code?

public class Test {
    public static void main(String[] args) {
        Sub sub = new Sub();
        System.out.println(sub.getWidth());
    }
}

class Sub extends Base {    
    private Dimension size;
    
    public Sub() {        
        this.size = new Dimension(50, 50);
    }
    
    public Dimension getSize() {
        return size;
    }
}

class Base {    
    private int width;
    private int height;
    private Dimension size = new Dimension(20, 20);
    
    Base() {        
        this.width = getSize().width;
        this.height = getSize().height;
    }
    
    Dimension getSize() {
        return size;
    }
    
    int getWidth() {
        return width;
    }
    
    int getHeight() {
        return height;
    }
}
Explanation
NullPointerException is thrown after attempt of (Base) superclass constructor to handle the object state, which is received from getSize() method, which was redefined in Sub class. 'Sub' class initializes the 'size' variable only in it's constructor, so getSize() returns 'null' after calling.

Where is "import java.awt.Dimension;" ?

2018 Jul 27, 5:15:15 PM

Java
Java Quiz
Start Quiz

or Read more about Java Quiz

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback