Domanda

My java book has the following practice question:

public class Person(){...}

public class Teacher extends Person{...}

And it asks which of the following are true statements:

1: Teacher inherits the constructors of Person.

2: Teacher can add new methods and private instance variables.

3: Teacher can override existing private methods of Person.

The book says 2 and 3 are true. I said only 2 is true.

I have read that subclasses do indeed inherit private methods and member fields yet they cannot be directly accessed. So my question is how would one override existing private methods if they cannot be directly accessed? And why would one want to override private methods if they were probably made private for a good reason?

È stato utile?

Soluzione

3: Teacher can override existing private methods of Person.

That's wrong.

Private methods/fields of super class are not visible/inherited to sub classes. So, You can't override them.

Try it with an example

Altri suggerimenti

methods are inherited only if they are public or protected or has no access modifier. private cannot be inherited. I think what the book meant Teacher can 'override' private method of Person via creating a similar method name with broader or similar access modifier, since Teacher does not see the method. This is called Method Shadowing. it's either the book chose the wrong word using override instead of shadowing, or gave wrong answer.

Example:

public class Person(){
  private void sayHello(){...}    
}

public class Teacher extends Person{
   public void sayHello(){...}
}

JLS §8.2

Members of a class that are declared private are not inherited by subclasses of that class.

As others have said, a subclass cannot override the private methods of an inherited class. This is specifically the purpose of the protected keyword. It is for functions and data members that are supposed to be private to other objects, but still accessible to subclasses. If the private functions could be accessed by the sub class, there would be no purpose for the protected keyword then.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top