Daiwik Daarun
Daiwik Daarun

Reputation: 3974

Creating a method for an abstract class in java

I am trying to create a method for an abstract class in Java.

Say B and C extend abstract A.

Within A there is a method void doSomething(???)

I want B.doSomething(B) to work, but B.doSomething(C) should not. I also want C.doSomething(C) to work, but C.doSomething(B) should not. Is this possible?

EDIT: I want the method to be defined in A

EDIT 2: Using LaShane's answer...

A b = new B();
A c = new C();
b.doSomething(c);//how can I prevent this?

Upvotes: 2

Views: 60

Answers (1)

Iłya Bursov
Iłya Bursov

Reputation: 24229

You can implement it in this way:

abstract class A<T> {
    abstract void doSomething(T obj);
};

class B extends A<B> {

    @Override
    void doSomething(B obj) {
    }

};

class C extends A<C> {

    @Override
    void doSomething(C obj) {
    }

};

Upvotes: 2

Related Questions