Java子类条件调用父类构造及instanceof报错问题求解
Let's walk through fixing your code and addressing the issues you're facing step by step.
First, Fix the Parent Class
Your original parent class used static fields for the DTOs, which is incorrect—static fields are shared across all instances, so every Super/Derived object would overwrite the same values. Switch to instance fields instead:
public class Super { protected DTO1 dto1Object; protected DTO2 dto2Object; public Super(DTO1 dto1Object) { this.dto1Object = dto1Object; } public Super(DTO2 dto2Object) { this.dto2Object = dto2Object; } }
Correct the Subclass Implementation
Java requires that super() (or this()) is the first statement in a constructor, so you can't do conditional logic directly inside the constructor. Instead, use a static factory method to handle type checking before creating the subclass instance. Here's the fixed Derived class:
public class Derived extends Super { // Constructors delegate directly to parent (no logic here) public Derived(DTO1 dto1Object) { super(dto1Object); } public Derived(DTO2 dto2Object) { super(dto2Object); } // Static factory method to handle conditional instance creation public static Derived create(Object obj) { if (obj instanceof DTO1) { return new Derived((DTO1) obj); } else if (obj instanceof DTO2) { return new Derived((DTO2) obj); } else { // Handle invalid input (throw exception or return null based on your needs) throw new IllegalArgumentException("Unsupported object type: " + obj.getClass().getName()); } } // Example method to perform type-specific operations public String processString(String str) { if (dto1Object != null) { // Execute operations for DTO1 type System.out.println("Working with DTO1: " + dto1Object); return "DTO1 processed: " + str; } else if (dto2Object != null) { // Execute operations for DTO2 type System.out.println("Working with DTO2: " + dto2Object); return "DTO2 processed: " + str; } else { throw new IllegalStateException("No valid DTO instance present"); } } }
Why Your Original Code Failed
Let's break down the errors you encountered:
- Nested method definition: You tried to define
Functioninside thecreatemethod—Java doesn't allow methods nested inside other methods. Move helper methods to the class level. - Incorrect
instanceofcheck:create(dto1Obj) instanceof DTO1will never be true. Thecreatemethod returns aDerivedinstance, which is a subclass ofSuper, not aDTO1. Instead, check which parent field is non-null to determine the type. - Static fields causing shared state: Using static
dto1Obj/dto2Objmeant all instances shared the same data, leading to unexpected behavior when comparing withequals(). - Invalid constructor logic: You tried to run conditional code before calling
super(), which violates Java's constructor rules.
Usage Example
To use the corrected code:
// Create instances via the factory method DTO1 myDto1 = new DTO1(); Derived derivedFromDto1 = Derived.create(myDto1); DTO2 myDto2 = new DTO2(); Derived derivedFromDto2 = Derived.create(myDto2); // Perform type-specific operations derivedFromDto1.processString("test"); derivedFromDto2.processString("test");
内容的提问来源于stack exchange,提问作者intruder

