构造继承抽象类的子类时不使用super()的技术问题咨询
super()? Hey there! As someone new to Java OOP, this is a super common point of confusion—let’s break it down clearly.
First, let’s get the hard rule out of the way: If your parent abstract class (VehicleClass) only has a parameterized constructor (no no-arg constructor), Java requires that every subclass constructor explicitly calls a parent constructor using super() with matching arguments. The compiler won’t let you skip this because it needs to initialize the parent class’s fields before the subclass can do its own setup.
That said, there are ways to structure your code so you don’t have to write super() directly in every subclass constructor you use day-to-day. Here are two practical approaches:
1. Add a No-Arg Constructor to the Abstract Parent Class
If you can modify the VehicleClass abstract class, adding a protected no-arg constructor lets subclasses skip explicit super() calls (the compiler will automatically invoke this no-arg constructor for you). You can even set default values for the parent’s fields here to avoid nulls:
public abstract class VehicleClass { private String type; private String vehicleName; // New protected no-arg constructor with defaults protected VehicleClass() { this.type = "unknown"; this.vehicleName = "unnamed"; } // Existing parameterized constructor public VehicleClass(String vType, String vName) { type = vType; vehicleName = vName; } // Your abstract methods go here... }
Now your subclass can have a constructor without any super() call:
public class Car extends VehicleClass { public Car() { // Compiler automatically runs super() (the no-arg parent constructor) } }
2. Use a Static Factory Method in the Subclass
If you can’t modify the parent class (or don’t want a no-arg constructor), you can hide the super() call inside a static factory method. This way, you never write super() in the code that creates subclass instances—you just call the factory method instead:
public class Car extends VehicleClass { // Private constructor that calls super (only used inside the class) private Car(String type, String name) { super(type, name); } // Public static factory method to create Car instances public static Car createCar(String vehicleType, String vehicleName) { return new Car(vehicleType, vehicleName); } }
To create a Car instance, you’d use:
Car myToyota = Car.createCar("sedan", "Toyota Camry");
The super() call still happens (in the private subclass constructor), but you don’t have to write it in your main code flow.
Important Note
There’s no way to truly avoid invoking the parent constructor—Java’s object initialization rules mandate that the parent class is initialized before the subclass. The approaches above just let you avoid writing super() explicitly in the code you interact with most often.
内容的提问来源于stack exchange,提问作者Joji

