I’m just starting to learn Java and I just got to the if-else-else if
statements section on CodeAcademy. I tried using the if else
statement in a method, but I’m not receiving the variable value when I call it, only the if-else statement. I’m guessing this is a very small mistake.
(This is my first post so if I’m using any of the features incorrectly, let me know)
Thank you!
public class Dog{
String name;
double weight;
int age;
public Dog(String dogName, double dogWeight, int dogAge){
String name = dogName;
double weight = dogWeight;
int age = dogAge;
if (dogAge == 10){
System.out.println("He's getting a bit older!");
} else if (dogAge < 10) {
System.out.println("He is still young!");
} else if (dogAge > 10){
System.out.println("Make sure he is healthy!");
}
}
public static void main(String[] args){
Dog coco = new Dog("CoCo", 15.67, 11);
System.out.println(coco.age);
}
}
The output I get from this is:
Make sure he is healthy!
0
>Solution :
In your constructor, you’re declaring new variables local to the method that happen to have the same name as your object’s properties.
public Dog(String dogName, double dogWeight, int dogAge){
String name = dogName;
double weight = dogWeight;
int age = dogAge;
To overwrite your object’s properties, you can remove the type declaration in order to refer to an existing variable.
public Dog(String dogName, double dogWeight, int dogAge){
name = dogName;
weight = dogWeight;
age = dogAge;
You can also utilize the this
object, which disambiguates between the object’s properties and similarly named variables. It helps with readability as well.
public Dog(String dogName, double dogWeight, int dogAge){
this.name = dogName;
this.weight = dogWeight;
this.age = dogAge;