有一个没有抽象方法的抽象类有什么意义? [英] What's the point in having an abstract class with no abstract methods?

查看:28
本文介绍了有一个没有抽象方法的抽象类有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以有一个抽象类实现其所有方法——其中没有抽象方法.

Can have an abstract class implementing all of its methods-- with no abstract methods in it.

例如:

public abstract class someClass { 
    int a; 
    public someClass (int a) { this.a = a; } 
    public void m1 () { /* do something */ } 
    private void m2 () { /* do something else */ }  
}

与拥有与具体类相同的类相比,拥有这样一个抽象类有什么优势(如果有的话)?

What's the advantage, if any, of having such an abstract class compared to having the same class as a concrete one instead?

我能想到的是,当我将它声明为抽象时,它不会被实例化.但是,我可以通过将其具体化并使其构造函数私有来获得相同的效果.

One i can think of is that, when i declare it as abstract, it won't be instantiated. however, i can have the same effect by making it concrete and its constructor(s) private.

TIA.

//==================

//==================

我能想到的另一种用途:

One other use I can think of:

它可能正在扩展另一个抽象类或实现一个接口而不实现该类的抽象方法——尽管它实现了自己的所有方法.不管它值多少钱.

it may be extending another abstract class or implementing an interface without implementing that class's abstract methods-- although it is implementing all methods of its own. for whatever it' worth.

推荐答案

它有一个概念上的意义:这个类有一个行为,它本身没有任何意义.

It has a conceptual meaning: this class has a behaviour which makes no sense on its own.

诚然,如果没有明确定义的扩展点(即抽象方法),很难想象这样的场景,但有时它会是您问题的合理准确模型.

Granted, it's difficult to imagine such a scenario without well-defined extension points (i.e. abstract methods), but occasionally it will be a reasonably accurate model of your problem.

你可以有这样的东西:

public abstract class ObjectWithId {
    private final String id;

    public ObjectWithId( String id ) {
       this.id = id;
    }

    public final String getId() {
       return id;
    }
}

然后你可以扩展它来声明不同类型的具有 id 的对象.这里有一个完全指定和实现的行为,但对子类可能表现出的任何其他行为没有限制.

And then you can extend it to declare different types of objects that have ids. Here you have a fully specified and implemented behaviour but no restriction on any other behaviours subclasses may exhibit.

请注意,对同一事物进行建模的更简洁的方法是使用组合而不是继承.

Note though that a much neater way to model the same thing is to use composition instead of inheritance.

public final class ObjectWithId<T> {
    private final String id;
    private final T ob;

    public ObjectWithId( String id, T ob ) {
       this.id = id;
       this.ob = ob;
    }

    public String getId() {
       return id;
    }

    public T getObject() {
       return ob;
    }
}

但是在引入泛型之前(直到 Java 1.4 版),这不会像抽象类解决方案那样优雅和明显更好,因为您不得不牺牲类型安全.

But before generics were introduced (up to Java version 1.4), this wouldn't have been as elegant and obviously better than the abstract class solution because you'd have had to trade in type safety.

这篇关于有一个没有抽象方法的抽象类有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆