Limited inheritance in java

I know that

class A  { } 
class B extends A  { }  
class C extends B { }

is completely legal and I can

C obj = new C();
obj.anyMethodfromA();

perhaps. Now the question is, if I do not want to refer to classes A methods in class C , then methods of class B should be inherited. Is it possible?

C anotherObj = new C();
anotherObj.anyMethodfromA(); //can be illegal?
anotherObj.anyMethodfromB(); //should be legal.
+4
source share
5 answers

You cannot remove methods classAfrom classC, all you can do is override the classA method in classC and throw an UnsupportedOperationException , like

class C extends B { 

    @override
    public void someMethodWasInClassA() {
        throw new UnsupportedOperationException("Meaningful message");
    }

}
+6
source

. , .

+1

Java . , A protected, .

A C, . .

( , , ++ friend: private A B a friend A. )

0

C is-a A at the moment , but it looks like you don't want this. So instead, C has-a B or B has-a A.

Prefer composition over inheritance.

0
source

With, interfaceyou can use some dexterity to hide methodFromA, but you cannot remove it.

class A {

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

class B extends A {

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

class C extends B {
}

interface D {

    public void methodFromB();

}

class E extends B implements D {

}

public void test() {
    // Your stuff.
    C obj = new C();
    obj.methodFromA();
    // Make a D
    D d = new E();
    d.methodFromB();
    // Not allowed.
    d.methodFromA();
    // Can get around it.
    E e = (E) d;
    e.methodFromA();
}
0
source

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


All Articles