user5459652
user5459652

Reputation:

Restricted 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();

is possible. Now question is this What if I don't want to access class A methods in class C only class B methods should be inherited. Is this possible?

C anotherObj = new C();
anotherObj.anyMethodfromA(); //can be illegal?
anotherObj.anyMethodfromB(); //should be legal.

Upvotes: 4

Views: 693

Answers (5)

Michael Lloyd Lee mlk
Michael Lloyd Lee mlk

Reputation: 14661

At the moment C is-a A, however it sounds like you don't want that. So rather than have that maybe C has-a B or B has-a A.

Prefer composition over inheritance.

Upvotes: 0

rajuGT
rajuGT

Reputation: 6404

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

class C extends B { 

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

}

Upvotes: 6

Bathsheba
Bathsheba

Reputation: 234785

There is no such fine-grained inheritance in Java. Once you've marked A methods protected, that extends down the entire heirarchy.

A workaround would be to reimplement the class A methods in class C, throwing appropriate run-time exceptions. But you cannot enforce a compile time failure.

(Note that you could achieve what you want in C++ with friendships: you'd mark the methods private in class A and make class B a friend of class A.)

Upvotes: 0

OldCurmudgeon
OldCurmudgeon

Reputation: 65841

You can use some sleight of hand using interface to hide the methodFromA but you cannot actually 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();
}

Upvotes: 0

R.G.
R.G.

Reputation: 861

Restricting access for certain subclasses is not possible. You could use interfaces instead to add certain a functionality to a specific class in addition to inheritance.

Upvotes: 1

Related Questions