2

My question is quite easy, but I cannot figure out how to implement what I want.

I would like to implement a method which, depending of the given parameter, returns one subClass or another (I understand that I could have this behavior in some class to make the development more object oriented, but I'm still learning).

So I thought of this solution, but it does not compile.

public abstract class A(){ //some code } public class B extends A(){ //some code } public class c extends A(){ //some code } public static void main(String[] args) { System.out.println("input: "); Scanner console = new Scanner(System.in); String input=console.nextLine(); A myObject = getObject(input); } public static <? extends A> getObject(String input){ if(input.indexOf("b") != -1){ return new B(); } if(input.indexOf("c") != -1){ return new C(); } return null; } 
3
  • And what is the error? Please post the full compiler error. Commented Oct 4, 2014 at 19:40
  • Generics won't be useful here, they don't exist during program execution (when input is evaluated). Commented Oct 4, 2014 at 19:41
  • You haven't get a return type on your method. Commented Oct 4, 2014 at 19:42

2 Answers 2

2

First, you need to remove the brackets (()) from your class definitions:

public abstract class A { //some code } public class B extends A { //some code } public class C extends A { //some code } 

Second, getObject should just return A:

public static A getObject(String input){ if(input.indexOf("b") != -1){ return new B(); } if(input.indexOf("c") != -1){ return new C(); } return null; } 
Sign up to request clarification or add additional context in comments.

Comments

1

In your example, I don't see any need to use generics. Your method can simply return A :

public static A getObject(String input){ if(input.indexOf("b") != -1){ return new B(); } if(input.indexOf("c") != -1){ return new C(); } return null; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.