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开发者_Go百科 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?
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)
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.
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.
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
}
}
精彩评论