简体   繁体   English

如何访问在构造函数(JAVA)中初始化的对象?

[英]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.

相关问题 Java - 如何允许类的所有方法访问在构造函数中初始化的数组? - Java - How to allow all methods of a class to access an array initialized in constructor? Java:在构造函数中初始化的修改和访问变量 - Java: Modify & access variable initialized in constructor 当Java中的对象被部分初始化时(构造函数中发生异常) - When objects in Java are partially initialized ( an exception occurs in the constructor ) 如何访问java中类构造函数内的数组列表? - How do I access an array list inside of a class constructor in java? 如何使用外部方法调用模拟在构造函数中初始化的对象? - How to mock objects initialized in constructor using an external method call? 如何使用 EasyMock 和 PowerMock 模拟构造函数内部初始化的最终变量? - How to mock final variable initialized inside constructor ,using EasyMock and PowerMock? 为什么以及如何在不由Java构造函数初始化的情况下初始化实例变量? - why and how instance variable get initialized without getting initialized by constructor in Java? 如何让参数化构造函数链中的派生类访问使用派生构造函数初始化的基类的字段 - How to let a derived class in a parameterized constructor chain access fields of the base class that are initialized using the derived constructor 如何在处理/ Java Eclipse项目中没有构造函数的情况下访问其他类中的主类对象? - how to access main class objects in other classes without a constructor in a processing/java eclipse project? 如果我们不创建该类的任何对象,如何在 java 中初始化静态数组 - how are static arrays initialized in java if we are not creating any objects of that class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM