0
Whats a Constructor? Java
example Ant z = new Ant(); < if this is an instance of class Ant, is this using a Constructor or is "new" the constructor?
5 Answers
+ 2
@David, no problem; you are asking a lot of the logical beginner questions. We've all been there :)
So in your example:
Ant a = new Ant();
Ant // the type of the variable; specified what the variable contains
a // the (name of the) variable
= // assignment operator; assigning the "value" on the right to the variable on the left
new // java keyword, used to create a new instance
Ant() // constructor used to create new instance of class Ant
; // end of statement
So on the left you are declaring a variable named a of type Ant.
On the right you are creating a new instance of class Ant with the code "new Ant()". By assigning this to the variable a (using the = operator), you are pointing the variable a to the new instance of Ant you have created.
You can now use variable a to do things to/with the Ant by calling methods on it, like so:
a.doSomething(); // assuming class Ant has a method doSomething()
An argument is a variable you pass to a method. For instance:
Ant a = new Ant(); // variable a points to an instance of Ant
Ant b = new Ant(); // variable b points to another instance of Ant
a.equals(b); // check if they are the same ant
+ 5
Hi @David, actually Ant() is the constructor; it constructs a new instance of class Ant.
No that a constructor is in a way like a method (it does something, and can take arguments) but is unlike a method in that it doesn't specify a return type (an instance of the class is the return type)
In this case you are using a constructor without any arguments, a.k.a. the no-arg constructor; you are not passing it any variables.
You could also use a Constructor to set certain values, like this:
class Ant{ // class
int size; // variable
public Ant(int size){ // constructor, taking 1 argument
this.size = size; // set size of this instance to given size
}
}
If you do not specify a constructor, the compiler will add the no arg construct for you.
If you do add a constructor, it will not add it for you. If you then also want a no-arg constructor, you have to add it yourself. (A class can have multiple constructors.
Hope this helps! Let me know if you have additional questions
+ 1
when i create this in main..
Ant a = new Ant();
which part of this is the instance of class?
can you explain to me like below plz...
Ant<<class a<<<< object ect...
sorry im just getting confused with how specific java is i dont really understand what a argument is either... thanks
+ 1
Another example to hopefully explain argument better:
lets say we have a method to add two numbers and it returns the sum
public int sum(int a, int b){
return a + b;
}
// int a and b are the arguments passed to the method sum
0
thank you marit well explained and much appreciated.