rashid
rashid

Reputation: 264

java how to prevent class from being derived more than two levels?

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

Answers (4)

Kishor Sharma
Kishor Sharma

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

mabroukb
mabroukb

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

Peter Lawrey
Peter Lawrey

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

Sebastian
Sebastian

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

Related Questions