Results 1 to 4 of 4
  1. #1
    coltragon is offline Senior Member
    Join Date
    Dec 2009
    Posts
    104
    Rep Power
    0

    Default methods and packages

    hello,

    i know this may be a little noob question but anyways i can't sort it out.
    i'm making a little rpg game...
    i wanted to make a method buyClothes wich the user can purchase clothes.
    because the method has to be public(the main needs to acces it)
    i couldnt make it in that file. because when i tried to make a public method it gives me illegal start of type error.

    so i decided to make a new class file in this package...
    and put my method buyClothes in there.

    now how can i acces my method in the main file?
    because when i type
    Java Code:
    buyClothes();
    it says it can't find method... how to acces a method from another file?
    Beginner in Java Programming, Please don't trust my anwsers blind please :D

  2. #2
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Accessing methods from other classes is done in 2 ways, depending on the method, if it's static or non-static.
    Static methods are accessed by typing the name of the class in front of the method:
    Java Code:
    MyClass.myMethod();
    Non-static methods can only be accessed through an object-instance of the class:
    Java Code:
    MyClass a = new MyClass();
    a.myMethod();

  3. #3
    coltragon is offline Senior Member
    Join Date
    Dec 2009
    Posts
    104
    Rep Power
    0

    Default

    thanks a lot
    Beginner in Java Programming, Please don't trust my anwsers blind please :D

  4. #4
    thomasdevos's Avatar
    thomasdevos is offline Member
    Join Date
    Feb 2010
    Posts
    19
    Rep Power
    0

    Default

    hi coltragon,
    i guess below code can help you, good luck
    Java Code:
    public class AccessOneMethod {
    	public static void main(String[] args) {
    		Person p = new Person();
    		p.buyClothes();
    	}
    }
    
    class Person{
    	public void buyClothes(){
    		
    	}
    }
    i hold 7 years develop exp. now i start a thread to share my knowlege about a j2ee project. welcome to participate.Study Java Through Real Java Project

Similar Threads

  1. Replies: 8
    Last Post: 04-16-2012, 11:00 PM
  2. Packages
    By urbim in forum Eclipse
    Replies: 2
    Last Post: 07-02-2009, 02:01 PM
  3. Replies: 3
    Last Post: 02-12-2008, 11:03 AM
  4. Using packages
    By prfalco in forum New To Java
    Replies: 5
    Last Post: 01-31-2008, 10:38 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
  •