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

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

问题描述

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

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天全站免登陆