简体   繁体   English

创建对象时调用方法

[英]Invoke method while creating an object

Guys please tell me what is the construction when I call method while creating an object? 伙计们,请告诉我创建对象时调用方法的构造是什么?

for example: Person p = new Person().get..... 例如:Person p = new Person()。get .....

If you want to create an Instance of the Object with new and call the Method while creating that Object than you can call that Method in the Constructor of that Objects Class 如果要使用new创建对象的实例并在创建该对象时调用该方法,则可以在该Objects类的构造方法中调用该方法。

class Person {
  Person() {
    method();
  }
}

If you create your Object (Person) with this constructor the Method will be invoked. 如果使用此构造函数创建对象(人),则将调用Method。

If you want to call a Method after creating the Object. 如果要在创建对象后调用方法。

Person person = new Person();
String name = person.getName();

or 要么

String name = new Person().getName();

I guess patter Builder is what are you looking for 我想Patter Builder是您在寻找什么

public class Computer {

    //required parameters
    private String HDD;
    private String RAM;

    //optional parameters
    private boolean isGraphicsCardEnabled;
    private boolean isBluetoothEnabled;


    public String getHDD() {
        return HDD;
    }

    public String getRAM() {
        return RAM;
    }

    public boolean isGraphicsCardEnabled() {
        return isGraphicsCardEnabled;
    }

    public boolean isBluetoothEnabled() {
        return isBluetoothEnabled;
    }

    private Computer(ComputerBuilder builder) {
        this.HDD=builder.HDD;
        this.RAM=builder.RAM;
        this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled;
        this.isBluetoothEnabled=builder.isBluetoothEnabled;
    }

Computer comp = new Computer.ComputerBuilder(
                "500 GB", "2 GB").setBluetoothEnabled(true)
                .setGraphicsCardEnabled(true).build();

The closest thing that comes to mind may be singleton, but it doesn't create new objects. 我想到的最接近的东西可能是单例,但它不会创建新对象。 Person p = Person().getInstance()? 人p = Person()。getInstance()?

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

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