Java - Subclass calls a supers constructor, which calls a subclass method instead of its own

I'll start with an example code:

class A {
    public A() {
        f(); //When accessed through super() call this does not call A.f() as I had expected.
    }

    public void f() {} //I expect this to be called from the constructor.
}

class B extends A {
    private Object o;

    public B() {
        super();
        o = new Object(); //Note, created after super() call.
    }

    @Override
    public void f() {
        //Anything that access o.
        o.hashCode(); //Throws NullPointerException.
        super.f();
    }
}

public class Init {
    public static void main(String[] args) {
        B b = new B();
    }
}

This program throws NullPointerException. When an object b enters the constructor of its superclass Aand calls a method call f()that is overridden by class B B.f(), instead of A.f()what I would expect.

I thought that the superclass should not have known if it was a subclass or not, but of course, this can be used by the class to determine if it was a subclass or not? What is the reason for this? Is there any workaround if I really want to be A.f()called instead B.f()?

Thanks in advance.


Next question:

. , , . , , , , . "" , . :

class A {
    private boolean isSubclassed = true;

    public A() {
        f(); //A.f() unsets the isSubclassed flag, B.f() does not.
        if(this.isSubclassed) {
            System.out.println("I'm subclassed.");
        } else {
            System.out.println("I'm not subclassed.");
        }
    }

    public void f() {
        this.isSubclassed = false;
    }
}

class B extends A {
    public B() {
        super();
    }

    @Override
    public void f() {}
}

public class Init {
    public static void main(String[] args) {
        new B(); //Subclass.
        new A();
    }
}

:

I'm subclassed.
I'm not subclassed.

A , . , . ? ?

+3
4

NullPointerException , B ( A). f(), B, f() B.

@Override
public void f() {
    //Anything that access o.
    o.hashCode(); //Throws NullPointerException as o has not been initialised yet
    super.f();
}

, .

+2

- . , , .

+1

. f() super super. subclass override.

 class A{
 public A() {
    f(); // It call the subclass overided method.
  }
 // This method is hide due to override.
  public void f() {
    } 
 }

class B extends A {
// This method is called before constructor where Object o is Null, hence you
// got NullPointerExcetion.
@Override
public void f() {
    // Anything that access o.
    o.hashCode(); // Throws NullPointerException.
    super.f();
 }
}
0
class A {
    public A() {
             System.out.println(1);
         f(); 
             // where super(),this will be called by subclass ,but subclass o is null 
    }
    public void f() {
        System.out.println(4);
    }
}
0

All Articles