tgrosinger
tgrosinger

Reputation: 2579

Generic Methods and inheritance in Java

Lets say class C and D extend class B which extends class A

I have a methods in class E that I want to be able to use either an object C or object D in. I know that class A provides all the methods that I need. How can I go about writing a method that lets me pass either a object C or object D as a parameter?

Am I right in thinking I need to make a generic class? If so does anyone have specific examples that are closer to what I need that this which only seems to tell me how to use the existing collection class?

Upvotes: 0

Views: 323

Answers (4)

Andreas Dolk
Andreas Dolk

Reputation: 114757

class A {
  public String hello(){return "hello";}
}
class B extends A{}
class C extends B{}
class D extends B{}

The method hello is available in all subclasses B,C and D.

So in E, do something like:

private void test() {
  System.out.println(hello(new A()));
  System.out.println(hello(new B()));
  System.out.println(hello(new C()));
  System.out.println(hello(new D()));
}

public String hello(A a) {
  return a.hello();
}

and you can pass instances of A,B,C or D

BTW - generics are not necessary in this scenario (as far as I understood it)

Upvotes: 6

Amir Afghani
Amir Afghani

Reputation: 38511

class A { 

}

class B extends A { 


}

class C extends B { 


}

class D extends B { 

}

class E { 

    public void test ( A a ) { 
        // c or d will work fine here
    }

}

Upvotes: 0

Edwin Buck
Edwin Buck

Reputation: 70899

public void doSomething(A input) {
  input.methodInA();
  input.secondMethodInA();
  ...
}

Polymorphism will run an possible overridden code implement in C or D, you don't need to do anything other than call the method.

Upvotes: 1

Rom1
Rom1

Reputation: 3207

If C and D have A as their common ancestror and A provides all needed methods, then your method should simply take an instance of A as a parameter. You do not need a generic method, unless I misunderstood your question.

Upvotes: 2

Related Questions