简体   繁体   中英

What is the proper style for implementing a skeleton class?

What is the proper style for implementing a skeleton class in Java?

By skeleton I mean a class that provides a skeleton utility code, but needs a subclass to implement some of the parts.

In C++ I would just add pure virtual methods into the class, but Java has a strict distinction between interfaces and classes, so this is not an option.

Basically the patter should be something like this:

class Skel { 
  void body() {
    this.action1();
    this.action2();
  }
};

class UserImpl : extends A {
   void action1() {
      impl;
   }

   void action2() {
      impl;
   }
}

/* ... snip ... */

Skel inst = new UserImpl();

/* ... snip ... */

inst.body();

Abstract methods in Java are similar to virtual methods in C++.

You need to declare an abstract class Skel with abstract methods, and implement them in the subclass:

public abstract class Skel {

    public void body() {
        this.action1();
        this.action2();
    }

    abstract void action1();
    abstract void action2();

}
abstract class Skel {abstract void action1();
    abstract void action1();
    abstract void action2();
    public void body() {
        action1();
        action2();
    }
}

class UserImpl extends Skel {
    @Override
    public void action1() {
        //...
    }
    @Override
    public void action2() {
        //..
    }
}

Use Abstract Class or even better extract common interface so that you classes are referenced by it.

interface CommonInterface {
    void action1();
    void action2();
    void body(); 
}

abstract class Skel implements  CommonInterface{

    public void body() {
        action1();
        action2();
    }
}

class UserImpl extends Skel {

    @Override
    public void action1() {
        //...
    }

    @Override
    public void action2() {
        //..
    }
}

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