Jump to content

Simply Use a method from another class in same package


needhelpquick

Recommended Posts

You either have to make that object from that class and call it, e.g

 
//Other file:
Class Thing {
     String name;
 
     public String getName(){ ... }
 
}
 
 
// Main
Class main{
    public static void main(){
        Thing thing = new Thing();
 
         System.out.println(" My name is " + thing.getName()
    
   }
}

Or make the method static, e.g

 

When you have a static method it is saying that you do not need to create an instance of this object to use the method. Thus static methods cannot use fields from it's the class, so they usually take input.

 
//Other file:
public Thing{
       public static String getName(){
            return "John";
      }
}
 
 
 
// Main
public static void main(){
    String name = Thing.getName();
    System.out.println("My name is" + name);
 
}
 
Edited by Qubit
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...