calling a function in java without declaring a object

3.9k views Asked by At

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?

4

There are 4 answers

0
AudioBubble On

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

0
Sarthak Mittal On

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");
}
}
3
Ted Hopp On

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){ ...
0
SMA On

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.