1

I'm new in java, I want to call method class from implemented Class with interface without know class name "ClassA", which only know Object c and I have 2 file.

File (1) CobaInterface.java

package cobainterface;

public class CobaInterface {

    public static void main(String[] args) {

        ImplementedClass implementedClass = new ImplementedClass();

        ClassA clsA = new ClassA();
        implementedClass.myMethodFromClassA(clsA);
    }

}

class ClassA{
    public Integer getTwo(){
        return 2;
    }
}

interface MyInterface {
    public void myMethod();

    //here interface
    public void myMethodFromClassA(Object c);
}

File (2) : ImpementedClass.java

package cobainterface;

public class ImplementedClass extends CobaInterface {
    public void myMethodFromClassA(Object c) {
        //System.out.println(c.getTwo()); <- wrong when call method c.getTwo()
    }
}

How about if I want to call method getTwo() from ClassA without know Class Name, which only know Object c from file (2) as describe in code above. Thanks for advance.

1 Answer 1

2

You should use generic types so the implementation knows what the object will be,

interface MyInterface<T> {
    public void myMethod();

    //here interface
    public void myMethodFromClassA(T c);
}

The impl becomes,

package cobainterface;

public class ImplementedClass Implements MyInterface<ClassA> {
    public void myMethodFromClassA(ClassA c) {
        //System.out.println(c.getTwo()); <- wrong when call method c.getTwo()
    }
}

All together,

class Scratch {
    public static void main(String[] args) {

        ImplementedClass implementedClass = new ImplementedClass();

        ClassA clsA = new ClassA();
        implementedClass.myMethodFromClassA(clsA);
    }

}

class ImplementedClass implements MyInterface<ClassA> {
    @Override
    public void myMethod() {

    }

    @Override
    public void myMethodFromClassA(ClassA c) {
        System.out.println(c.getTwo());
    }
}

class ClassA {
    public Integer getTwo() {
        return 2;
    }
}

interface MyInterface<T> {
    void myMethod();

    void myMethodFromClassA(T c);
}

You could also do a cast

System.out.println((MyClass)c.getTwo());

but you will lose all benefit of type saftey.

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

3 Comments

You could also do a cast - maybe should check with instanceof
completely slipped my mind, there's a few ways to be safer with casting. @ScaryWombat. mentions.
@DarrenForsythe Thanks for help,, that's opened my mind about java,,

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.