【问题标题】:Whats the best pratice to create constant variables and subclasses inhertience them什么是创建常量变量和子类继承它们的最佳实践
【发布时间】:2020-06-23 21:35:32
【问题描述】:

我不确定是否有标准或好的做法可以在父类中创建常量变量,然后子类重用。

public class parentA{
protected static final String name = Constants.SYS_NAME;
protected static final String code = Constants.CODE;

}

public class son extends parentA{

private static void main(String[] args) 
    { 
        System.out.println("Name: "+name); 
        System.out.println("Code: "+code ); 
    } 

}

【问题讨论】:

  • 有更好的做法吗?

标签: java constants extends


【解决方案1】:

一种常见的做法是使用interface 作为常量。

interface MyInterface {
    public static final int X = 10;
    public static final int Y = 20;
}

public class Main {
    public static void main(String[] args) {
        System.out.println(MyInterface.X);
    }
}

输出:

10

【讨论】:

猜你喜欢
  • 2020-01-02
  • 1970-01-01
  • 2015-07-05
  • 2013-04-10
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 1970-01-01
  • 2010-10-04
相关资源
最近更新 更多