Reputation: 264
In java I need to prevent Level1 class (look at following sample code) from being derived for more than two levels. Deriving till Level2 and Level3 is fine but if class is derived by Level4 then exception should be thrown. Look at following code sample.
Code sample:
class Level1 {
private int level = 1;
protected Level1() throws RuntimeException {
level++;
//System.out.println(level);
if (level > 2) {
throw new RuntimeException("Can't implement more than 2 levels");
}
}
}
class Level2 extends Level1 {
protected Level2() {
}
}
class Level3 extends Level2 {
Level3() {
}
}
class Level4 extends Level3 {
Level4() {
}
}
From above code sample I am not proposing solution using static int level counter. I am just trying to explain the issue.
Is it possible in Java by implementing some logic or by using some API where Level1 base class can count number of levels it has been derived?
Upvotes: 0
Views: 683
Reputation: 599
You can make level3 class final then it cannot be extended by any class. A class that is declared final cannot be subclassed.
Upvotes: 0
Reputation: 701
introspection api can help you handle that, try something like :
protected Level1() throws RuntimeException {
if (getClass().equals(Level1.class)) {
return;
}
if (getClass().getSuperclass().equals(Level1.class)) {
return; // first level or inheritance
}
if (getClass().getSuperclass().getSuperclass().equals(Level1.class)) {
return; // second level or inheritance
}
// else
throw new RuntimeException("Can't implement more than 2 levels");
}
by the way, why do you want to do that ?
Upvotes: 5
Reputation: 533620
You can look at the getClass().getSuperclass() etc to check there is not more than N levels to your class.
Its a baffling requirement however. :P
Upvotes: 3
Reputation: 8005
You can use reflection in the constructor and walk the inheritance chain of this.getClass() to see the nesting level. Actually a test for this.getClass().getSuperClass() == Level1.class should do the trick already.
Upvotes: 10