0

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?

4 Answers 4

6
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)

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, well that is actually how I had it set up already, cool. I am not at a stage where I can test the code yet so just wanted to check. Thanks
2

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.

Comments

1
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.

Comments

0
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
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.