简体   繁体   中英

Java - Writing the body of an abstract class in the subclass constructor

When defining an abstract class, it is possible to create an instance of that class by writing the body of the abstract methods at object definition, like this:

AbstractClass obj = new AbstractClass() {   
   protected String description() {   return this.description;   }   
};

I would like to do something similar, but inside the constructor of a sub-class. Something like this:

public class AbstractClass {
   String description;
   public AbstractClass(String description){
       this.description = description;
   }
   protected abstract String description();
}
public class ActualClass extends AbstractClass {
   public ActualClass(String description){
       super(description) {
       protected String description() {    return this.description;    }
       };
   }
}

Now, the code above doesn't work. How could I do something similar?

You don't do it in constructor, but in the class itself:

public abstract class AbstractClass {
    String description;
    public AbstractClass(String description){
        this.description = description;
    }
    protected abstract String description();
}

public class ActualClass extends AbstractClass {
    public ActualClass(String description){
        super(description);
    }

    protected String description() {
        return this.description;
    }
}

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