Results 1 to 2 of 2
  1. #1
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Blog Entries
    Rep Power

    Default How can I call a method of this Inner Class?

    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()
    		return new PDestination(s);
    	public static void main(String[] args)
    		Parcel5 p = new Parcel5();
    		Destination d = p.destination("Moon");
    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().

    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 ?

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    New Zealand
    Rep Power

    Default 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

  1. Inner class method call
    By d915172 in forum New To Java
    Replies: 3
    Last Post: 11-11-2010, 10:40 PM
  2. Trying to call a method from sub class
    By TheNewGuy in forum New To Java
    Replies: 4
    Last Post: 10-17-2010, 08:08 AM
  3. Replies: 2
    Last Post: 05-01-2010, 09:59 AM
  4. How to call a method from another class?
    By jboy in forum New To Java
    Replies: 8
    Last Post: 09-09-2009, 08:29 AM
  5. How to call a class within a method
    By Manfizy in forum New To Java
    Replies: 3
    Last Post: 03-19-2009, 01:34 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts