简体   繁体   中英

calling a function in java without declaring a object

i am new to java is there is any possible way of calling a function within same class without creating a object for the class my program is

public class Puppy{

   public Pup(String name){

      System.out.println("Passed Name is :" + name ); 
   }
   public static void main(String []args){

     public Pup( "tommy" );
   }
}

i want to call function pup without creating object for it ,is it possible?

You can declare the method to be static:

public static void Pup(String name){
    ...
}

As an aside: you should use standard Java naming conventions and start your method name with a lower-case letter:

public static void pup(String name){ ...

Try this:

public class Puppy{

public static void Pup(String name){
  System.out.println("Passed Name is :" + name ); 
}
public static void main(String []args){
  Pup("tommy");
}
}

You can define Pup as statis method like:

public static void Pup(String name){
  // This constructor has one parameter, name.
  System.out.println("Passed Name is :" + name ); 

}

And from main call it like:

Pup("tommy");

There are couple of issues in your code:

  • You don't have valid return type for your method Pup. If you dont return anything you should add void as return type.
  • You can't use public or any access modifier within any method. So you need remove public from method call.

I'm not sure but maybe.... Inside your main method, you can simply use this statement,

Pup("Your Name");

Your Pup method should have a valid return statement and use these modifiers,

public static  

if it's a returning method

public static void

if it's a void method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM