简体   繁体   中英

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.....

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

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

If you create your Object (Person) with this constructor the Method will be invoked.

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

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()?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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