-7
class a
{
----
}
class b extends a
{

}

But my class a not inherited into b how

Pramod Kumar
  • 7,914
  • 5
  • 28
  • 37
SIVA
  • 11
  • 2
  • 6
  • What behavior are you expecting, and what are you seeing? –  Jul 20 '12 at 12:35
  • 5
    Why do you not want to use the `final` keyword? That's specifically what the `final` keyword _does_. – David Jul 20 '12 at 12:39
  • @David Yes, it's a bit like asking how to make a field static without using the `static` keyword. It's doable but why? – biziclop Jul 20 '12 at 12:42
  • 2
    @biziclop: It tangentially reminds me of this question: http://stackoverflow.com/q/4464291/328193 Just an odd use of the language, and makes me think that there's something _behind_ the question that we're not seeing. Like the OP is trying to solve a higher-level problem and needs to step back for a moment to actually solve it, instead of trying to get SO to help with the current attempted "solution." – David Jul 20 '12 at 12:46
  • 1
    exact duplicate http://stackoverflow.com/questions/451182/stopping-inheritance-without-using-final – Nandkumar Tekale Jul 20 '12 at 12:51
  • 2
    @David or this was an interview question to test the applicant's knowledge of the programming language. – Jesper Jul 20 '12 at 12:57
  • 1
    @Jesper: Ah, could be. And interview questions _always_ make me wonder what is the core reason behind it, because they're _always_ contrived and have no core reason :) So many times I've wanted to hear a candidate say, "Why would you even do it that way?" – David Jul 20 '12 at 13:00

2 Answers2

9

What exactly is your question? How to prevent class a from being subclassed, but without making class a final?

Make all constructors of class a private. Provide a factory method for creating instances of a.

class a {
    // Private constructor
    private a() {
    }

    // Factory method
    public static a createA() {
        return new a();
    }
}
Jesper
  • 202,709
  • 46
  • 318
  • 350
2

Use following in your class constructor :

if (this.getClass() != A.class) {
    throw new RuntimeException("Subclassing not allowed");
}

But using this way, you will restrict inheritance at run time.

Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
  • 1
    Note though that this isn't a 100% safe method. If someone **really** wants to instantiate a subclass of A, they will be able to. – biziclop Jul 20 '12 at 12:58