Java inconsistent inheritance mechanics?

I think we already discussed this issue in this article here Inheritance in a simple Java explanation

But since the example here is a little simpler, and the point I want to clarify is different, I will take a picture.

First, consider two classes:

public class SuperClass{
    SuperClass() {
        foo();
    }

    public void foo() {
        System.out.println("Super.foo()");
    }

    public static void main(String[] args) {
            SuperClass tn = new DerivedClass();
            tn.foo();
    }
}

public class DerivedClass extends SuperClass{
    String i;

    TrickyB() {
        i = "aksjhdf";
    }

    public void foo() {
        System.out.println("In derived.foo() --> " + i);
    }
}

I (at least I think) understand the concepts of polymorphism, and I know why it DerivedClass.foo()is called when called

new DerivedClass();

I see inconsistency here:

At the time we call c'tor of DerivedClass, c'tor SuperClassis called implicit (so to speak, like the first line of the c'tor derivative).

So, Super c'tor is DerivedClassnot fully initialized, which makes working with this class useless. This point is reflected in the output of this program.

In derived.foo() --> null
In derived.foo() --> aksjhdf

:

DerivedClass.foo()? , - .

- . , .

BTW: , SuperClass.foo() , , , "" .

: . , , c'tor SuperClass, DerivedClass.foo()!

SuperClass.foo() ?

+3
5

DerivedClass.foo()? , - .

. . , . new .

, SuperClass.foo()

, , . . . . .

SuperClass - .

, . , , , . , , , . DerivedClass, DerivedClass, .

SuperClass.foo() ?

. . , .

+7

++, Java , . .

. , , , , ( this ). ( ) , .

+3

Why is DerivedClass.foo() called?

Java. , , .

How would I call SuperClass.foo() in my case?

: super.foo();

0

DerivedClass.foo() DerivedClass. Foo() . , , SuperClass.foo(). - . foo() SuperClass, super.foo(). , DerivedClass.foo() i, i.

0

, (, , , ) . :

public class SuperClass{
    SuperClass() {
        privateFoo();
    }

    public void foo() {
        privateFoo();
    }

    private void privateFoo() {   // cannot be overridden since it private
        System.out.println("Super.foo()");
    }

}

foo , . , / , .

0

All Articles