简体   繁体   English

在 Java 中访问不同类的静态成员时避免代码重复

[英]Avoid code-duplication while access different classes' static members in Java

I'm writing an abstract class and have some sub-classes extend it.我正在编写一个抽象类并有一些子类扩展它。 I have the exact same method with the same implementation in the sub-classes, and I'm wondering if there's a way to avoid the code duplication.我在子类中有完全相同的方法和相同的实现,我想知道是否有办法避免代码重复。 The problem is that although the code is completely identical in every class, it uses a static variable of the class.问题是虽然代码在每个类中完全相同,但它使用了类的静态变量。 Is there a way to have the method written only once (in the abstract class, for example) and have the method access the static member " NAME " from the class type of the current object?有没有办法让该方法只编写一次(例如在抽象类中)并让该方法从当前对象的类类型访问静态成员“ NAME ”?

In other words, is there a way to implement the method getName() only once, and return the NAME static variable of the current type of class?换句话说,有没有办法只实现一次getName()方法,并返回当前类的NAME静态变量?

public abstract class Car {
    public abstract String getName();
}

public class Bus extends car{
    
    private static final String NAME = "Bus a Bus A";
    
    public String getName() {
        return Bus.NAME;
    }
}

public class Taxi extends car{

    private static final String NAME = "TAXiiii";

    public String getName() {
        return Taxi.NAME;
    }
}

public class Motor extends car{

    private static final String NAME = "motor hehe";

    public String getName() {
        return Motor.NAME;
    }
}

Why not simply pass the name to the super constructor?为什么不简单地将名称传递给超级构造函数? Although this removes the need for Car to be abstract , because you can simply return the name from its getName method instead.尽管这消除了Carabstract的需要,因为您可以简单地从其getName方法返回名称。

public class Car {
    private final String name;
    
    public Car(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public class Bus extends Car {

    private static final String NAME = "Bus a Bus A";

    public Bus() {
        super(NAME);
    }
}

public class Taxi extends Car {

    private static final String NAME = "TAXiiii";

    public Taxi() {
        super(NAME);
    }
}


public class Motor extends Car {

    private static final String NAME = "motor hehe";

    public Motor() {
        super(NAME);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM