简体   繁体   English

在不声明对象的情况下在Java中调用函数

[英]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 我是Java的新手,是否有任何可能的方法可以在同一类中调用函数而无需为我的程序的类创建对象

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? 我想调用函数pup而不为其创建对象,这可能吗?

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: 顺便说一句:您应该使用标准的Java命名约定,并以小写字母开头您的方法名称:

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: 您可以将Pup定义为statis方法,例如:

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. 您的方法Pup没有有效的返回类型。 If you dont return anything you should add void as return type. 如果不返回任何内容,则应添加void作为返回类型。
  • You can't use public or any access modifier within any method. 您不能在任何方法中使用public或任何access修饰符。 So you need remove public from method call. 因此,您需要从方法调用中删除public。

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, 您的Pup方法应具有有效的return语句,并使用这些修饰符,

public static  

if it's a returning method 如果是返回方法

public static void

if it's a void method 如果是无效方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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