Results 1 to 2 of 2
- 02-05-2012, 01:18 AM #1
Senior Member
- Join Date
- Nov 2011
- Location
- Turkey
- Posts
- 378
- Blog Entries
- 24
- Rep Power
- 2
How can I call a method of this Inner Class?
I am expecting d.writeLabel() not to work, since writeLabel method is in an Inner - Class that is only in the scope of the method destination().Java Code:package myPackage; public class Parcel5 { public Destination destination(String s) { class PDestination implements Destination { private String label; private PDestination(String whereTo) { label = whereTo; } public String readLabel() { return label; } public void writeLabel() { System.out.println(label); } } return new PDestination(s); } public static void main(String[] args) { Parcel5 p = new Parcel5(); Destination d = p.destination("Moon"); d.writeLabel(); } }
I guess my understanding of a class being in the scope of a method is not clear. How is this innerclass I have in scope of a method if I can simply call methods from it ?
- 02-05-2012, 01:38 AM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,544
- Rep Power
- 11
Re: How can I call a method of this Inner Class?
To be able to call a method all you need is a variable of the right type.
You have a variable d that is of type Destination, therefore you can call any of the Destination methods like readLabel() or writeLabel(). It does not matter in the least that d refers to an instance of a local type PDestination. You have a reference to a Destination, so you can use Destination methods.
What you cannot do is call methods or constructors that are specific to a PDestination. You cannot call the PDestination constructor from outside the destination method because PDestination is a local class.
Similar Threads
-
Inner class method call
By d915172 in forum New To JavaReplies: 3Last Post: 11-11-2010, 09:40 PM -
Trying to call a method from sub class
By TheNewGuy in forum New To JavaReplies: 4Last Post: 10-17-2010, 07:08 AM -
how call from inner class(anonymous or not), a method of parent class?
By lse123 in forum AWT / SwingReplies: 2Last Post: 05-01-2010, 08:59 AM -
How to call a method from another class?
By jboy in forum New To JavaReplies: 8Last Post: 09-09-2009, 07:29 AM -
How to call a class within a method
By Manfizy in forum New To JavaReplies: 3Last Post: 03-19-2009, 12:34 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks