开发者

Java:How to call Implemented method from interface name

I don't know how interface works for my problem but I have read that its possible by interface here

Problem: I have created an interface which has All the declaration of the methods its around 3000+ I am implementing these methods in 3 different classes, now I want to call the methods from Interface in my main file, 开发者_StackOverflowreason I can need any method from any class and I cant extend more than one class so i thought about using interface.

Can I do this Answers are appreciated.

Update: using extend I can use super.methodName(); So that i am not creating an object. I can split these methods in different interfaces or different classes but I must access the methods without creating the object Please the link to understand what i want to do.

Update2: Interface ABC // public int go() function is declared here

Class XYZ implements ABC

method go(object imp)  
{.....}   

Another class

Class PQR extends/implements ABC 
{
   // some code
   int ret = super.go(this); OR int ret = obj.go(this)
} // What Should I use I now ABC is my interface but dont know where is it implemented so i want to call the go function how can I do this Please Explain what should i use.

Thanks


When you call a method on an interface, it actually calls the implementing method on the concrete class. It doesn't matter that you have an insane number of methods or how many classes you have. e.g.

List list = new ArrayList();
list.size(); // actually calls ArrayList.size()

BTW: There is only a relatively small number of classes which have 3000 lines, let alone 3000 methods. I assume this is generated code.


Let be an interface Z and classes A and B implementing Z. Z has a method m1().

Z z1 = new A();
Z z2 = new B();
z1.m1(); // actually calls m1 as implemented in A even if the object is declared as Z.
z2.m1(); // different implementation of the same method m1

You declare z1 as being of type Z, but the implementation is A. Same thing for z2 but for B.


If you're are talking about generated code I think what you need is to load a class at run-time. You can't call the methods of an interface without having those methods implemented in a concrete class and (without having) an interface "reference object" that points to an instantiated object (that implements that interface).

So a solution would be the use of Reflection, over which I suggest you take a look. This will give you an idea how to load a class, call methods and pass arguments at run-time, not at compile time. (i.e. you can call those methods after the dinosaur class was generated)

A small example can be found at: http://java.sun.com/developer/technicalArticles/ALT/Reflection/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜