可以在同一个包中通过类名调用方法,而无需创建类的对象或在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中没有继承”,但我已经修复了这个问题,我想确认这是否可能或不
最佳答案
如果方法声明为静态
,则可以使用语法ClassName.methodName()
调用方法,例如
class ClassName {
static void methodName() {
//...//
}
}
有关静态类成员的更多信息可以在 Java Tutorials 中找到。 .
关于java - 我可以在同一包下的另一个类中调用一个类的静态方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11327938/