File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes interface and concrete classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "interface and concrete classes" Watch "interface and concrete classes" New topic

interface and concrete classes

Kaustubh Patil
Ranch Hand

Joined: Aug 13, 2001
Posts: 164
If I have a reference of an interface assigned to a concrete class which implements that interface can I call methods that are defined in the implementing class but not declared in the interface ?

for example :

my interface is

my abstract class is

my concrete class is

my test class is

I cannot call method2 on the obj as it is not defiened in the abstract class though its there in TestConcrete.
If I make the refernce type as interface Testif still I cannot call method2 even though the reference points to TestConcrete.

As far as I understand the method calls are made on the type of the object the reference points to and not on the class type of the reference. So why are these calls not possible ? Why can I call only those methods that are declared in the interface / abstrace class ?

Kaustubh. Mumbai, India.
Nick George
Ranch Hand

Joined: Apr 04, 2004
Posts: 815
As far as I understand, the compiler knows the object only as the label you gave it when you named it, which was TestAbs in the case of obj. What constructer you used is all well and good, but to the compiler it IS a TestAbs. The solution is easy; just add a typecast, i.e.

[ May 27, 2004: Message edited by: Joseph George ]

I've heard it takes forever to grow a woman from the ground
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
If I've a reference of type A, then I can only use that reference to invoke methods defined as available to things of type A.

As mentioned, I could also use that reference to create a new reference of a different type by using a type cast. Then, the same rules apply to my new reference.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Kaustubh Patil
Ranch Hand

Joined: Aug 13, 2001
Posts: 164
Thanks Joe and Dirk. I did try that after I posted this query and it worked !!!
I agree. Here's the link:
subject: interface and concrete classes
It's not a secret anymore!