简体   繁体   English

我可以在同一程序包下的另一个类中调用一个类的静态方法吗?

[英]Can I call a static method of one class in another class under same package?

Can call a method by class name in same package without create object of class or without inheritance in java 可以在同一包中通过类名调用方法,而无需创建类的对象或在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.");
    }
}

my question is not this as you seems my qestion is this "Can call a method by class name in same package without create object of class or without inheritance in java" but i have fix this i want to confirm is this possible or not 我的问题不是这个,因为您看来我的问题是“可以在没有创建类的对象或不继承Java的情况下,在同一个程序包中通过类名调用方法”,但我已解决此问题,我想确认是否可能

You can call a method with the syntax ClassName.methodName() if the method is declared static , eg 如果方法声明为static ,则可以使用语法ClassName.methodName()调用该方法。

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

More info about static class members can be found in the Java Tutorials . 有关静态类成员的更多信息,请参见Java教程

Make your method static then you can call that method by class name. 将您的方法设为静态,然后可以通过类名调用该方法。

class A {
static void display(){

    System.out.println("Called..");
}
}

In same package you can call it as . 在同一软件包中,您可以将其称为。

A.display();

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

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