JProg
JProg

Reputation: 189

Class with non-default constructor

I'm trying to create a LinearNode class with a non default contractor but passing the two arguments. I tried this but I'm getting an error. Any idea why?

public class LinearNode<T> (T elem, LinearNode<T> node){
        private LinearNode<T> next = node;
        private T element = elem;
    }

Thanks!

Upvotes: 0

Views: 400

Answers (3)

Tobias Ritzau
Tobias Ritzau

Reputation: 3327

You have mixed the constructor with the class definition. The constructor is a special member function and should be defined more or less like a method (with no return type and the same name as the class).

public class LinearNode<T> {
    private LinearNode<T> next;
    private T element;

    LinearNode(T elem, LinearNode<T> node) {
        next = node;
        element = elem;
    }
}

Upvotes: 2

gnomed
gnomed

Reputation: 5565

Your constructor declaration needs to be separate from your class declaration. Like so:

public class LinearNode<T>{
    private LinearNode<T> next;
    private T element;
    LinearNode<T>(T elem, LinearNode<T> node){
        next = node;
        element = elem;
   }
}

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240860

You can't have (arguments) with class declaration

And also

you can't specify access specifier private for local variables

Upvotes: 1

Related Questions