程序需要一个包含静态和非静态数据的对象。 所有数据类都应该实现/扩展相同的类/接口(interface),以便能够执行以下操作:
Color color1 = new Navy();
为了简化它,让我们以颜色存储类为例。 这些颜色类存储颜色,并可以根据它们自己的颜色和传递的颜色计算自定义混合。
interface Color {
public static final int hex;
public int mix;
}
class Navy implements Color {
public static final int hex = 0x000080;
public int mix;
public Navy(int otherColor) {
mix = otherColor -128 +hex;
}
}
class Maroon implements Color {
public static final int hex = 0x800000;
public int mix;
public Maroon(int otherColor) {
mix = otherColor -56 +hex;
}
}
class DarkMagenta implements Color {
public static final int hex = 0x8B008B;
public int mix;
public DarkMagenta(int otherColor) {
mix = otherColor +180 +hex;
}
}
我知道接口(interface)中的所有变量都是静态最终的,并且在使用抽象类时,可以声明必须实现的抽象方法,但不能声明抽象变量。
什么是不需要所有 getter 并节省编写代码的通用解决方案?
编辑:
两种接口(interface)方式:
interface Color {
public static final int hex=0;
public int mix=0;
}
class Navy implements Color {
public static final int hex = 0x000080;
public int mix;
public Navy(int otherColor) {
mix = otherColor -128 +hex;
}
}
class Maroon implements Color {
public static final int hex = 0x800000;
public int mix;
public Maroon(int otherColor) {
mix = otherColor -56 +hex;
}
}
class DarkMagenta implements Color {
public static final int hex = 0x8B008B;
public int mix;
public DarkMagenta(int otherColor) {
mix = otherColor +180 +hex;
}
}
和抽象类方式:
abstract class Color {
public static final int hex=0;
public int mix;
}
class Navy extends Color {
public static final int hex = 0x000080;
public int mix;
public Navy(int otherColor) {
mix = otherColor -128 +hex;
}
}
class Maroon extends Color {
public static final int hex = 0x800000;
public int mix;
public Maroon(int otherColor) {
mix = otherColor -56 +hex;
}
}
class DarkMagenta extends Color {
public static final int hex = 0x8B008B;
public int mix;
public DarkMagenta(int otherColor) {
mix = otherColor +180 +hex;
}
}
不要做我想做的事:
//this works but
Navy color1 = new Navy(9);
System.out.println(color1.hex);// 128
// not this
Color color2 = new Navy(9);
System.out.println(color2.hex);// 0
所有颜色都应该是 Color 的子成员。
最佳答案
不存在“抽象变量”这样的概念。 它要么是变量,要么是常量。 java中的常量是使用final修饰符声明的。如果它是一个静态常量(静态意味着属于一个类,静态元素不能被继承),它必须在声明内或静态初始化 block 内初始化。
在接口(interface)中,您只能声明 public static final 字段(顺便说一句,所有这些修饰符都可以省略),并且一旦接口(interface)中不允许使用静态 block ,您就必须在其中提供值声明。
像这样,否则无法编译:
interface Color {
public static final int hex = 0x000080;
public int mix = 127;
}
关于java - 如何在java中使用数据类,而不使用getter方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70736392/