Reputation: 3
I have two child classes B and C which inherit from one parent class A. Is it possible that I can make certain functions of class A accessible in B but not in C in java?
Upvotes: 0
Views: 62
Reputation: 1097
If what you want is to forbid to call destroyEverything()
from class C:
public class A {
public void travel() {
System.out.println("Travel from A");
}
public void makePee() {
System.out.println("Call from A");
}
}
public class B extends A {
public void travel() {
super.travel();
System.out.println("Travel from B");
}
public void makePee() {
super.makePee();
System.out.println("Call from B");
}
}
Then, on C:
public class C extends A {
public void travel() {
super.travel();
System.out.println("Travel from C");
}
public void makePee(){
throw new UnsupportedOperationException("Not supported from C");
}
}
BUT, if what you want is to not inherit stuff from A, it is probably a flaw at the design of your class hierarchy and class C should not inherit from A.
Example of design flaw: Class A is Animal, class B is Beaver, and you want your class C Cadillac to inherit stuff from Animal since Animal already has the method travel.
Since maybe you don't want to inherit the method makePee (every animal urinates, but Cadillacs don't), it is better to move Cadillacs (class C) to another class hierarchy or find another class design
Upvotes: 0
Reputation: 21
As per my thinking it is not possible.
Let's see the one real time example-> A Parent have a two child then both are able to access parent property .it is there no restriction on that you can not use this or you can not use this.
And if you want to do like that then you can implicitly write logic in B class also
Upvotes: 0
Reputation: 11
Well i don't know a way to forbid it in the Code. But you could just override and then don'f fill them.
Upvotes: 1