1

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?

1
  • Not really, and a String isn't a Node. Commented Feb 14, 2015 at 1:26

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.