Middle
Is it possible to narrow the access level or change the return type when overriding a method?
sobes.tech AI
Answer from AI
The access level when overriding a method can only be the same or more permissive.
The return type can be the same as in the base class, or covariant (a subclass) for reference types. Primitive types require an exact match.
Example of covariant return:
class Animal {
// parent class
}
class Dog extends Animal {
// subclass
}
class AnimalFeeder {
// base class with method feed
public Animal feed() {
return new Animal();
}
}
class DogFeeder extends AnimalFeeder {
// subclass overriding the feed method
@Override
public Dog feed() { // covariant return type (Dog is a subclass of Animal)
return new Dog();
}
}