I’m currently studying abstract classes in Java, and I tried to run the abstract example in the lecture video I’m studying, but I’m not getting the results I’m expecting. (The lecture video didn’t show the results/didn’t run the code after, so I ran it myself.)
Here are the codes:
public abstract class AbstractClothing {
private int id;
public int getId() {
return id;
}
public void setId(int _id) {
this.id = _id;
}
protected abstract double getPrice();
protected abstract void display();
}
public class Socks extends AbstractClothing {
private double price;
public Socks(int _id, double price) {
this.setId(_id);
}
@Override
protected double getPrice() {
System.out.println(price); // I also don't know why there's println here, but I just followed the code in the video
return price;
}
@Override
protected void display() {
System.out.println("Price is " + this.getPrice());
System.out.println("Id is " + this.getId());
}
}
public class WorkingWithAbstractClasses {
public static void main(String[] args) {
Socks mySocks = new Socks(4, 4.50);
mySocks.setId(3);
mySocks.display();
}
}
The output I’m getting is:
0.0
Price is 0.0
Id is 3
I’m expecting the output to be like this:
4.50
Price is 4.50
Id is 3
I don’t understand why the price is 0.0 and not 4.50.
I tried to check the variable price and its value in debug mode (though I admit I’m not yet great at debugging), but it also says 0.0 there. Shouldn’t the value of price be 4.50 because I assigned price = 4.50 when I instantiated mySocks? (I’m not sure if it matters, but I’m using IntelliJ.)