【问题标题】:Can I call a static method of one class in another class under same package?我可以在同一个包下的另一个类中调用一个类的静态方法吗?
【发布时间】:2012-07-04 11:12:34
【问题描述】:

可以在同一个包中通过类名调用方法而无需创建类的对象或在java中无需继承

public class BoxWeight /*extends Box*/{
    public static void main(String[] args) {
        /*BoxWeight myCat = new BoxWeight();*/
        /*Box myAnimal = myCat;*/
        Box.testClassMethod();<------------ why this possible 
        /* myAnimal.testInstanceMethod();*/
    }   
}

public class Box /*extends Bicycle*/{

    public static void testClassMethod() {
        System.out.println("The class" + " method in Box.");
    }
    public void testInstanceMethod() {
        System.out.println("The instance " + " method in Box.");
    }
}

我的问题不是这个,因为你似乎我的问题是“可以在同一个包中通过类名调用方法,而无需创建类的对象或在 java 中没有继承”,但我已经解决了这个问题,我想确认这是否可能或不是

【问题讨论】:

  • 你的问题到底是什么?
  • 我不太确定你在问什么,但似乎你想在类而不是对象上调用方法,在这种情况下我猜你在谈论静态方法?
  • 我的问题不是这个,因为你似乎我的问题是这个“可以在同一个包中通过类名调用方法而不创建类的对象或在 java 中没有继承”但我已经解决了这个我想确认这是否可能

标签: java methods static


【解决方案1】:

如果方法声明为static,则可以使用语法ClassName.methodName() 调用方法,例如

class ClassName {
  static void methodName() {
    //...//
  }
}

更多关于静态类成员的信息可以在Java Tutorials找到。

【讨论】:

    【解决方案2】:

    将你的方法设为静态,然后你可以通过类名调用该方法。

    class A {
    static void display(){
    
        System.out.println("Called..");
    }
    }
    

    在同一个包中,您可以将其称为 .

    A.display();
    

    【讨论】:

      猜你喜欢
      • 2018-10-09
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2015-02-13
      • 2016-06-26
      • 1970-01-01
      相关资源
      最近更新 更多