Thursday, 15 September 2016

java - Method override returns null




I'm newbie in Java. So question might sound simple, but I'm stuck and can not figure out why this code returns null and 0.0 ?



file: Transport.java



public class Transport {

private String name;
private double price;


public Transport(String name, double price) {
this.name = name;
this.price = price;
}

public String carName() {
return name;
}

public double carPrice(){

return price;
}
}


file: Car.java



public class Car extends Transport{

protected String name;
protected double price;


public Car(String name, double price) {
super(name, price);
}

@Override
public String carName(){
return name;
}


@Override
public double carPrice(){
return price * 1.5;
}
}


file: Main.java



public class Main {
public static void main(String[] args) {


Car c = new Car("CarBrand", 1000);

System.out.println("Name: " + c.carName());
System.out.println("Price: " + c.carPrice());
}
}


Output




Name: null
Price: 0.0

Answer



You've declared separate name and price variables in Car, and never assigned a value to them - they're not the same as the name and price variables declared (and initialized) in Transport. So you're seeing the default values for String and double, basically. Get rid of those extra variables in Car, and use super.carPrice() to get the original price from Transport:



public class Car extends Transport {    
public Car(String name, double price) {
super(name, price);
}


@Override
public double carPrice(){
return super.carPrice() * 1.5;
}
}


Note that there's no need to override carName() at all unless you really want it to change behaviour.



I'd also suggest changing carName() and carPrice() to getName() and getPrice() to be more idiomatic.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...