0

I have below code which is giving error when i try to access the object's method. What is that i am doing wrong here.

public class Main{
public static void main(String[] args) {
    MyFirstObject myObj1 = new MyFirstObject();
    MySecondObject myObj2 = new MySecondObject();

MyGenerics mg = new MyGenerics();
System.out.println( mg.partTwo(myObj1, myObj2) );

}
}

class MyFirstObject{
    int value(){
        return 1;
    }
}
class MySecondObject{
    int value(){
        return 2;
    }
}

class MyGenerics {


   static <T,U> int partTwo (T o1, U o2) 
    { 
        System.out.println(o1.value()); 
                           return 1;
    } 
}

Error is : Main.java:31: error: cannot find symbol System.out.println(o1.value()); ^ symbol: method value() location: variable o1 of type T where T,U are type-variables: T extends Object declared in method partTwo(T,U) U extends Object declared in method partTwo(T,U) 1 error

5
  • Need to declare bounds on your type variables. Commented Jun 16, 2020 at 9:51
  • What is that method suppose to do and what do the Generic paramaters T and U represent in the code you wrote? Commented Jun 16, 2020 at 9:52
  • Your MyGenerics class is lacking type parameters <T,U>, which also need to be given on creation. Commented Jun 16, 2020 at 9:53
  • Why does class need generic parameters? I only need to create a generic method. Commented Jun 16, 2020 at 10:05
  • You need to tell the class somehow which classes T and U stand for. Commented Jun 16, 2020 at 10:55

1 Answer 1

2

When you pass T or U, java doesn't know what the object it is and what methods it contains, so you need some specification. For example, you can create an interface and implement it in classes.

Example:

public class Main {
    public static void main(String[] args) {
        MyFirstObject myObj1 = new MyFirstObject();
        MySecondObject myObj2 = new MySecondObject();

        MyGenerics mg = new MyGenerics();
        System.out.println(mg.partTwo(myObj1, myObj2));

    }
}

interface Action {
    int value();
}

class MyFirstObject implements Action {
    public int value() {
        return 1;
    }
}

class MySecondObject implements Action {
    public int value() {
        return 2;
    }
}

class MyGenerics {

    static <T extends Action, U extends Action> int partTwo(T o1, U o2) {
        System.out.println(o1.value());
        return 1;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Will this also ensure that it can accept only objects which implement interface containing value function.

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.