Setting inheritance field java vs constructor

I am new to Java. I had the following classes:

public abstract class Beverage {
    String description = "Unknown beverage";

    public String getDescription() {
        return description;
    }

    public abstract double cost();
}

and

public class DarkRoast extends Beverage {
    String description = "Dark roast";

    @Override
    public double cost() {
        return 0.99;
    }
}

When I create a new object DarkRoast:

Beverage beverage2 = new DarkRoast();

I expect it to have a description equal to "dark hot":

assertEquals("Dark roast", beverage2.getDescription());

But actually it is an "Unknown Drink". I know that I must implement the DarkRoast constructor, which sets the description, but I don’t know why, I don’t know how it works inside. Should the subclass field overwrite the superclass field?

+4
source share
6 answers

Should a subclass field not overwrite a superclass field?

- . , :

public DarkRoast()
{
    description = "Dark roast";
}

( cost() - , , ,

+4

getDescription Beverage (DarkRoast ), getDescription description, "Unknown beverage" > .

0

.getDescription() ; , Beverage, Beverage description ( ) Beverage.

, :

return this.description;

; :

public abstract class Beverage
{
    private final String description;

    public abstract Beverage(final String description)
    {
        this.description = description;
    }

    public final String getDescription()
    {
        return description;
    }
    // etc
}

// Subclass
public class DarkRoast
    extends Beverage
{
    public DarkRoast()
    {
        super("Dark Roast");
    }
}

, " " . Beverage , ! Beverage , .

0

, , . .

0

. , , .

, ,

public abstract String getDescription();

.

 BaseClass(String description) {
   this.description = description;
 }

child super

 ChildClass(String description) {
   super(description);
 }

super .

, -

  private void test() {
     System.out.println(super.description); //This will refer to parent class
     System.out.println(this.description);  //This will refer to child class
  }

, , .

0

, , : "" "DarkRoast", Beverage , / ( Java).

, , , DarkRoast, , , .

- , , , .

public class DarkRoast extends Beverage {
    String description = "Dark roast";

    public String getDescription() {
        return description;
    }

    public String getSuperDescription() {
        return super.description;
    }

    @Override
    public double cost() {
        return 0.99;
    }
    public static void main(String[] args) {
    DarkRoast b = new DarkRoast();
    System.out.println(b.getDescription());
    System.out.println(b.getSuperDescription());
}
}

, :

public static void main(String[] args) {
 Beverage b = new DarkRoast();
     DarkRoast b2 = new DarkRoast();
 System.out.println(b.description);
 System.out.println(b2.description);
}
0
source

Source: https://habr.com/ru/post/1529680/


All Articles