假设我有以下代码:
class A {
public static void main(String[] args) {
B b = new B();
System.out.println(b.getB() + " and count " + b.count);
}
}
class B {
private int b = 15;
int count = 0;
B() {
count++;
}
public int getB() {
return b;
}
}
输出为
15 and count 1
根据用途,哪个是可以的。
但是,count
是B类型对象的总数,每出现一个new B();
就加1。在代码中,第三行(其中有一个 new B();
)不应该这样做。我只是想要一个对类 B 的引用,以便访问它的属性和方法。
有没有一种方法可以在不实例化的情况下访问方法和属性?
最佳答案
However, count is the total amount of objects of type B, and it is added 1 every time a new B(); comes up.
错误。 count
是 B
类的实例变量,因此每次创建 B
的实例时,都会生成一个新的 count
变量在 B
构造函数中初始化为 0 并递增到 1。
为了计算 B
的所有实例,请将 count
设为静态变量。这样它就不会属于 B
的任何实例,您可以使用 B.getCount()
访问它(它也应该是静态的)。
class B {
private int b = 15;
private static int count = 0;
B() {
count++;
}
public int getB() {
return b;
}
public static int getCount() {
return count;
}
}
关于java - 访问另一个类的方法和属性而不实例化它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47035867/