Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

interface and concrete classes

 
Kaustubh Patil
Ranch Hand
Posts: 164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.



-Joe
[ May 27, 2004: Message edited by: Joseph George ]
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Kaustubh Patil
Ranch Hand
Posts: 164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Joe and Dirk. I did try that after I posted this query and it worked !!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic