Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call subclass constructor from parent in Java

so I'm learning about java inheritance and I just ran into a situation I don't know how to solve.

What I'm trying to do is to call a subclass constructor from the superclass. I don't know if this makes any sense, but I'll try to explain myself with an example.

public class Phone {
    private String brand;
    private int weight;

    public Phone(String brand, int weight) {
        this.brand = brand;
        this.weight = weight;
    }

    public Phone(String brand, int weight, String tech) {
        // Here it is where I'm stuck
        // Call SmartPhone constructor with all the parameters
    }
}

 

public class SmartPhone extends Phone {
    private String tech;

    public SmartPhone(String Brand, int weight, String tech) {
        super(brand, weight);
        this.tech = tech;
    }
}

Why would I want to do that?

I would like to be able to not have to deal with SmartPhone in the main.
I'd like to be able to do:

Phone nokia = new Phone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance
like image 248
Hibridinoisy Avatar asked Mar 25 '26 01:03

Hibridinoisy


1 Answers

Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance

this makes no sense. If you want a SmartPhone instance, you must call

Phone iphone = new SmartPhone("iPhone", 368, "4G");

You cannot call a sub-class constructor from a super-class constructor.

If you want the type of the Phone to be determined by the passed parameters, you can use static factory methods:

public class PhoneFactory {

    public static Phone newPhone (String brand, int weight) {
        return new Phone(brand, weight);
    }

    public static Phone newPhone (String brand, int weight, String tech) {
        return new SmartPhone(brand, weight, tech);
    }
}

Phone nokia = PhoneFactory.newPhone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = PhoneFactory.newPhone("iPhone", 368, "4G"); // <- SmartPhone instance
like image 87
Eran Avatar answered Mar 27 '26 13:03

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!