Jump to content

Simply Use a method from another class in same package


Recommended Posts

Posted (edited)

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

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