Home > Java > javaTutorial > Builder references

Builder references

Linda Hamilton
Release: 2025-01-14 10:08:43
Original
684 people have browsed it

Referências de construtor

  • Referencing a constructor uses the syntax: classname::new.

  • Can be assigned to a functional interface that has a constructor-compatible method.

Example with Parameterized Constructor

  • If the functional interface has a method with one parameter, the reference will be associated with the constructor with that parameter.

MyFunc myClassCons = MyClass::new;
MyClass mc = myClassCons.func("Testing");

  • Here, MyClass(String s) is the referenced constructor.

Example with Default Constructor

  • To reference the parameterless constructor, you must use a functional interface whose method also has no parameters.

MyFunc2 myClassCons = MyClass::new;
MyClass mc = myClassCons.func();

Use with Generic Classes

  • For generic classes, you can specify the type when creating the reference.

MyGenClass::new;

  • Thanks to type inference, specification is not always mandatory.

Type Inference

  • The reference to the constructor automatically selects the one that best suits the functional interface method.

// Demonstrates a constructor reference.
// MyFunc is a functional interface whose method returns
// a MyClass reference.
MyFunc interface {
MyClass func(String s);
}
class MyClass {
private String str;
// This constructor takes one argument.
MyClass(String s) { str = s; }
// This is the default constructor.
MyClass() { str = ""; }
// ...
String getStr() { return str; }
}
class ConstructorRefDemo {
public static void main(String args[])
{
// Creates a reference to the constructor of MyClass.
// Since MyFunc's func() method takes one argument,
// new references the parameterized constructor of MyClass
// and not the default constructor.
MyFunc myClassCons = MyClass::new; A constructor reference
// Creates an instance of MyClass using this constructor reference.
MyClass mc = myClassCons.func("Testing");
// Use the newly created MyClass instance.
System.out.println("str in mc is " mc.getStr());
}
}

The above is the detailed content of Builder references. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template