Reputation: 51
Can we initialize fields of a class in the same line as instantiating it?
public class LinkedQueueOfStrings {
private Node first;
private Node last;
private class Node
{
private String element;
private Node next;
}
public void enqueue(String s)
{
last.next = new Node(){element = s};
//Is there a way can do like this??
}
}
Is there a way we can we do like this,
last.next = new Node(){first = s};
assuming we don't have a constructor which initializes node with an element?
Upvotes: 1
Views: 1354
Reputation: 2009
I think that proper way to implement that you want is to provide respective constructor:
private static class Node {
public Node(String element, Node next) {
this.element = element;
this.next = next;
}
private String element;
private Node next;
}
or if you have many fields to initialize you can use Builder pattern.
Also note that your Node
class can be static
because it doesn't need enclosing class instance and just takes excess memory.
Upvotes: 0
Reputation: 58909
You can do this (if s
is final):
last.next = new Node() {{element = s;}};
which is equivalent to:
last.next = new Node() {
{
element = s;
}
};
which is an anonymous class with an initializer (effectively a constructor).
But that can cause problems later - for example the object won't be of type Node
, it will be of type LinkedQueueOfString$1
(or whatever the anonymous class gets called) which extends Node
.
You should probably just write a constructor, or set the fields separately:
last.next = new Node();
last.next.element = s;
Upvotes: 1