user5098268
user5098268

Reputation:

Why this code throws an NullPointerException?

im new to Java. I found this example in a book. I expected it to print "ab" or "abc", but it throws exception instead. Can somebody explain why it happens? Thanks in advance.

public class Test { 
    class A { 
        String str = "ab"; 

        A() { 
            printLength(); 
        } 

        void printLength() { 
            System.out.println(str.length()); 
        } 
    } 

    class B extends A { 
        String str = "abc"; 

        void printLength() { 
            System.out.println(str.length()); 
        } 
    } 

    public static void main(String[] args) { 
        new Test().new B(); 
    } 
} 

Here is the exception

Exception in thread "main" java.lang.NullPointerException
    at c.Test$B.printLength(Test.java:25)
    at c.Test$A.<init>(Test.java:13)
    at c.Test$B.<init>(Test.java:21)
    at c.Test.main(Test.java:30)

Upvotes: 1

Views: 127

Answers (2)

Kamal Pundir
Kamal Pundir

Reputation: 277

See error is in

  A() { 
       printLength();           
    } 

As when you do new B() then as B is sub class of A so the A() will be called as first statement of B() which is default in your case In A() you are trying to access str of class B but the initialization phase still not completed as the constructor of B() yet executed. So error occurs.

Hope I am able to help. Don't try to start execution from constructor as it is meant to initialize your attributes.

Thanks.

Upvotes: 0

P45 Imminent
P45 Imminent

Reputation: 8591

A is constructed before B. In A constructor you call printLength which is overridden in class B. But str in class B is not instantiated yet, and will be null.

Therefore you get a Null Pointer Exception.

Upvotes: 4

Related Questions