Tag: 类设计

大型内部类和私有变量

我经历过几次的一件事是服务类(比如JBoss服务)由于帮助器内部类而变得过大。 我还没有找到一个打破课堂的好方法。 这些助手通常是线程。 这是一个例子: /** Asset service keeps track of the metadata about assets that live on other * systems. Complications include the fact the assets have a lifecycle and their * physical representation lives on other systems that have to be polled to find * out if the Asset is still there. */ public […]

在什么情况下超类不应该是抽象的?

在这个线程中,我发现了一些有趣的时刻,如果类仅用作超类,则没有规则使其成为抽象的。 为什么这样? 谢谢

覆盖子类中的成员数据,用于超类实现?

在Java中,是否可以覆盖子类中的成员数据并将该重写版本作为超类实现中使用的数据? 换句话说,这就是我想要发生的事情,并且它没有发生: abstract public class BasicStuff { protected String[] stuff = { “Pizza”, “Shoes” }; public void readStuff() { for(String p : stuff) { system.out.println(p); } } } .. public class HardStuff extends BasicStuff { protected String[] stuff = { “Harmonica”, “Saxophone”, “Particle Accelerator” }; } 这个调用: HardStuff sf = new HardStuff(); sf.readStuff(); …打印Pizza和Shoes 。 […]

何时编写静态方法与实例方法的编码是否有经验法则?

我正在学习Java(和OOP),虽然它可能与我现在所处的位置无关,但我想知道是否可以分享一些常见的陷阱或良好的设计实践。

单例类如何使用接口?

我在许多地方读到单身人士可以使用接口。 有些我怎么也无法理解这一点。

如何在Java中的不同类之间共享数据

在Java中的不同类之间共享数据的最佳方法是什么? 我有一堆变量,不同的类以不同的方式在不同的文件中使用。 让我试着说明我的问题的简化版本: 这是我之前的代码: public class Top_Level_Class(){ int x, y; // gets user input which changes x, y; public void main(){ int p, q, r, s; // compute p, q, r, s doA(p,q,r); doB(q,r,s); } public void doA(int p, int q, int r){ // do something that requires x,y and p, q, r } public […]

非公共顶级类vs静态嵌套类

在我看来,非公共顶级类和静态嵌套类在创建辅助类时基本上执行相同的任务。 A.java public class A { public static main (String[] args) { AHelper helper = new AHelper(); } } class AHelper {} A.java public class A { public static main (String[] args) { A.AHelper helper = new A.AHelper(); } static class AHelper {} } 除了它们的引用方式之外,我认为创建助手类的两种方式之间差别不大。 它可能主要归结为偏好; 有没有人看到我错过的任何东西? 我想有些人会争辩说每个源文件有一个类更好,但从我的角度来看,在同一个源文件中有一个非公共顶级类似乎更干净,更有条理。

如何设计扩展

有一个Checkstyle规则DesignForExtension 。 它说:如果你有一个公共/受保护的方法,它不是抽象的,也不是最终的也不是空的,它不是“为扩展而设计的”。 请在Checkstyle页面上阅读此规则的说明以获取基本原理。 想象一下这个案子。 我有一个抽象类,它定义了一些字段和这些字段的validation方法: public abstract class Plant { private String roots; private String trunk; // setters go here protected void validate() { if (roots == null) throw new IllegalArgumentException(“No roots!”); if (trunk == null) throw new IllegalArgumentException(“No trunk!”); } public abstract void grow(); } 我还有一个植物的子类: public class Tree extends Plant { private […]