[英]how to access the Objects initialized inside constructor(JAVA)?
I have demonstrated an example below for my questions. 我在下面为我的问题演示了一个示例。
class B {
int name;
public int getName() {
return name;
}
public void setName(int name) {
this.name = name;
}
}
class A {
public A() {
// initializing object B
B b = new B();
}
}
class MainClass {
public static void main(String[] args) {
A a = new A();
}
}
How I access the object of B in the Mainclass which is initialized inside the class A Constructor? 如何访问在A类构造函数内部初始化的Mainclass中的B对象?
How about 怎么样
class A {
private B b;
public A() {
// initializing object B
b = new B();
}
public B getB () {
return b;
}
}
from mainClass 来自mainClass
A a = new A();
B b = a.getB ();
One way to achieve this would be to add a getter method inside your A
class which exposes the instance of B
: 实现此目的的一种方法是在
A
类中添加一个getter方法,该方法公开B
的实例:
public class A {
private B b;
public A() {
b = new B();
}
public B getB() {
return b;
}
}
Usage: 用法:
A a = new A();
B myB = a.getB();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.