【问题标题】:How to change the value of variable in interface by class who implement it in java? [duplicate]java - 如何通过在java中实现它的类来更改接口中变量的值? [复制]
【发布时间】:2017-01-25 14:53:56
【问题描述】:

我有接口:

public interface Myglobal 
{
public int Type =0;
}

然后我有类实现我的接口,例如:

Public class A implements Myglobal 
{
Public class A ()
{
this.type=1; // here error because type final in interface
}
}

我希望 evrey 类实现接口以更改变量类型的值...那么我如何使用 java 来实现呢?

【问题讨论】:

    标签: java


    【解决方案1】:

    我认为您应该使用抽象类来实现您想要做的事情,接口不能具有可以更改的值。它们也将是静态的,因为您不创建接口的实例。

    我还会使用 getter/setter 函数来处理值。

    public abstract class Myglobal 
    {
        private int Type =0;
    
        public void setType(int type) {
            this.Type = type;
        }
    
        public int getType() {
            return this.Type;
        }
    }
    
    public class A extends Myglobal 
    {
        public class A ()
        {
            this.setType(1);
        }
    }
    

    【讨论】:

    • 好的,所以我必须用抽象类替换接口...谢谢
    猜你喜欢
    • 2013-05-06
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    相关资源
    最近更新 更多