0
Java: How can the object of parent class call the parameterized constructor of child class while it's not the other way around?
Printer is a Class ans PrinterCumClass is the child class.... This is the main piece of code: int PRINTERNUMBER=3; Printer[] stock=new Printer[PRINTERNUMBER]; stock[0]=new PrinterCumClass("Hp",20,20.5,320.5); stock[1]=new PrinterCumClass("Cannon",30,20.5,146.5); Here we can see that Printer's obj is able to call child class's Constructor but it's not the other way around? How & Why? Please explain
4 odpowiedzi
+ 1
Post the code. You say stuff but without the code we can't know if it's the case.
Atleast the class declarations.
0
William Jönsson here's the complete code:
public class PrinterTest {
public static void main(String[] args) {
int PRINTERNUMBER=3;
Printer[] stock=new Printer[PRINTERNUMBER];
stock[0]=new PrinterCumClass("Hp",20,20.5,320.5);
stock[1]=new PrinterCumClass("Cannon",30,20.5,146.5);
for (Printer astock : stock) {
System.out.println(astock);
}
}
}
public class Printer {
String name;
int qunatity;
double price;
public Printer(String name, int qunatity, double price) {
this.name = name;
this.qunatity = qunatity;
this.price = price;
}
@Override
public String toString() {
return "name = " + name + "qunatity = " + qunatity + "price = " + price ;
}
}
public class PrinterCumClass extends Printer {
double imagedpi;
public PrinterCumClass(String name, int qunatity, double price,double dpi) {
super(name, qunatity, price);
0
Ok I get what you mean now. What you are doing when declaring the array (not object) is: "Printer[] stock" which means this is an array of Printer objects. And PrinterCumClass is a Printer object so then it works.
Imagine we have Animal and Dog.
Animal[] stock
stock[0] = new Dog
We can put a Dog inside the Animal array since Dog is an Animal.
0
> "Here we can see that Printer's obj is able to call child class's Constructor"
Printer[] stock = new Printer[PRINTERNUMBER];
stock[0] = new PrinterCumClass("Hp",20,20.5,320.5);
it is not able,
First you create object of PrinterCumClass, as child
child calls super() constructor of parent Printer
then object is assing to array of Printer[]
where you call child ?