Why can't we override the base class method with the private extended class method?

class One {
    void foo() { }
}
class Two extends One {
    private void foo() { /* more code here */ }
}

Why is this piece of code incorrect?

+3
source share
5 answers

I will try to incorporate ideas from other answers in order to come up with one answer.

First of all, let's see what happens in the code.

Look at the code

The class Onehas a private method foowith a package

: <
class One {
    // The lack of an access modifier means the method is package-private.
    void foo() { }
}

The class Twothat subclasses the class Oneand method foois overridden, but has an access modifier private.

class Two extends One {
    // The "private" modifier is added in this class.
    private void foo() { /* more code here */ }
}

Problem

Java , , Two, foo, .

?

, One:

class AnotherClass {
  public void someMethod() {
     One obj = new One();
     obj.foo();  // This is perfectly valid.
  }
}

foo One . (, AnotherClass , One.)

, Two obj One?

class AnotherClass {
  public void someMethod() {
     One obj = new Two();
     obj.foo();  // Wait a second, here...
  }
}

Two.foo , One.foo . .

, .

  • - Java.
+10

, , Java private foo, One. ,

One obj = new Two();
obj.foo();

, private foo of Two , obj.foo(), One, , t21 > , Two. , , obj - , , -

One obj = Math.random() < 0.5? new One() : new Two();
obj.foo();

, obj a One Two. , One. foo private in Two, obj, One, , private.

+1

, . , - - , - .

One , , . , , . , , Two , . One, , One.

+1

.

Two, Two, , foo . Two , One. foo, . .

0

- . Two One:

One v = new Two();

, foo v? One, , One ( ) foo. .

0

Source: https://habr.com/ru/post/1796476/


All Articles