This site requires JavaScript, please enable it in your browser!
Greenfoot back
xbLank
xbLank wrote ...

2017/12/27

Constructor Overloading

xbLank xbLank

2017/12/27

#
Say I have the Class Sheep and the 2 parameters 'speed' and 'rotation'. Speed is optional, rotation is not. How do I use Constructor Overloading to avoid nulling? I can't really get it to work.
xbLank xbLank

2017/12/27

#
#Solved I forgot to assign the devault value and java did not like that at all.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Sheep extends Actor
{
    private int speed,rot;
    public Sheep(int rotation)
    {
        rot = rotation;
        speed = 0 //default value
    }
    public Sheep(int rotation,int sheepSpeed)
    {
        this(rotation);
        speed = sheepSpeed;
    }
}
danpost danpost

2017/12/28

#
You could doubly overload the constructor as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public Sheep()
{
    this(0, 0);
}
 
public Sheep(int rotation)
{
    this(rotation, 0);
}
 
public Sheep(int rotation, int sheepSpeed)
{
    rot = rotation;
    speed = sheepSpeed;
}
By the way, all primitive type fields are automatically given a default value ('false' for booleans and '0' for all others); so, whatever the issue was, it was not what you purported here:
일리아스 wrote...
I forgot to assign the devault value and java did not like that at all.
It must have trying to tell you something else.
xbLank xbLank

2017/12/28

#
As I mentioned: There only is one optional parameter. I dont see a point in double overloading.
davmac davmac

2017/12/28

#
#Solved I forgot to assign the devault value and java did not like that at all.
The following compiles just fine for me:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import greenfoot.*;
 
public class Sheep extends Actor
{
    private int speed,rot;
    public Sheep(int rotation)
    {
        rot = rotation;
    }
    public Sheep(int rotation,int sheepSpeed)
    {
        this(rotation);
        speed = sheepSpeed;
    }
}
So, I don't think the issue is what you thought it was.
xbLank xbLank

2017/12/28

#
Hmmm.. thats weird. Thank you tho!
You need to login to post a reply.