简体   繁体   中英

How do i create multiple objects for child classes using parent class constructor(super())?

class Noodle {

double lengthInCentimeters;
double widthInCentimeters;
String shape;
String ingredients;
String texture = "brittle";

Noodle(double lenInCent, double wthInCent, String shp, String ingr) {
 
 this.lengthInCentimeters = lenInCent;
 this.widthInCentimeters = wthInCent;
 this.shape = shp;
 this.ingredients = ingr;
 
}

public void cook() {
 
 this.texture = "cooked";
 
}

public static void main(String[] args) {
 Pho phoChay = new Pho();
 System.out.println(phoChay.shape);
 
 }
}
class Pho extends Noodle {
Pho(){
 super(30.0,0.64,"flat","rice flour");
}
}

I want to create one more Pho object with different parameters how do I do it? for eg

A lengthInCentimeters of 20.0.

A widthInCentimeters of 0.85

A shape of "inflated

ingredients of "wheat flour"

Just create required args constructor matching super:

public class Pho extends Noodle{

    public Pho(double lenInCent, double wthInCent, String shp, String ingr) {
        super(lenInCent, wthInCent, shp, ingr);
    }
}

So you can create all kinds of noodles you need:

public class Main {

    public static void main(String[] args) {
        Noodle pho = new Pho(30.0,0.64,"flat","rice flour");
        Noodle anotherPho = new Pho(11.0,0.33,"round","bone flour");
    }
}

Extend the Noodle class, have a no parameter constructor in the child class that calls the parent super constructor with the desired parameters.

Here is some sample code:

class Pho extends Noodle
{
    public Pho()
    {
        super(20.0, .85, "inflated", "wheat flour");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM