Inheritance: weaker method availability in a subclass

what is the need to use such a rule in java:

"a subclass cannot weaken the accessibility of a method defined in a superclass"

+4
source share
4 answers

If you have a class with a public method

public class Foo {
    public void method() {}
}

This method is available and therefore you can

Foo foo = new Foo();
foo.method();

If you add a subclass

public class Bar extends Foo {
    @Override
    public /* private */ void method() {}
}

If it was private, you cannot perform

Foo bar = new Bar();
bar.method();

In this example, a Baris Foo, so it should be able to replace Foowherever expected.

, . . ( .)

+2

, .

,

protected void a() { } // visible to package and subclasses

public void a() { }    // visible to all
protected void a() { } // visible to package and subclasses

void a() { }           // visible to package
private void a() { }   // visible to itself

,

class A {
    public void a() { }
}

class B extends A {
    private void a() { }
}

A instance = new B();
instance.a(); // what does this call? 

, B a. , a B B.


() ().

- . , - , .

+2
class Person {
    public String name() {
        return "rambo";
    }
}

// subclass reduces visibility to private
class AnonymousPerson {
    private String name() {
        return "anonymous";
    }
}

: Person, AnonymousPerson. , , name().

class Tester {
    static void printPersonName(Person p) {
        System.out.println(p.name());
    }
}

//ok
Tester.printPersonName(new Person());

, a Person AnonymousPerson, . " ".

Tester.printPersonName(new AnonymousPerson());
+1

. , , IFlying, as:

public interface IFlying {
    public void fly();
}

, :

public class Bird implements IFlying {
    private void fly(){
        System.out.println("flap flap");
    }
}

, IFlying fly. . ? , , fly .

Consequently, accessibility could not be more restrictive in implementation.

0
source

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


All Articles