在java编程中,能对接口中的成员变量进行修改么(能的话怎么改)?
来源:百度知道 编辑:UC知道 时间:2024/06/08 17:52:12
interface stuinfor{
static int no = 20052359;
int year = 2005;
String dep = "软件工程";
public int age();
public void showInfor();
}
补补基础吧,interface的所有成员变量都被声明为最终静态的,也就是常量。修改是可以通过继承的方式重写的,例子:
public class inter implements b {
public static void main(String[] args) {
System.out.println(a);
}
}
interface a {
int a = 2;
}
interface b extends a {
int a = 6;
}
最后的输出结果为:6
楼上的第6条做个补充,还可以是抽象类~~~
乖乖£稀饭,看了楼上哥们给出那么多关于 interface 的基本资料,你已经很清楚 interface 里不能定义变量了。
这个限制是非常合理的,因为 interface 的主要目的之一就是要让我们只声明一个类型所提供的服务(功能)但不提供那些服务的任何具体实现的细节。
变量这种提供数据存储和读取的机制是实现细节的一部分(所以只能在提供实现细节的 class 机制里出现)。
如果你选择定义 StuInfor 这个接口然后在 Student 类中实现该接口,你应该以相应的一对 setXxx 和 setXxx 方法(所谓的 getter/setter 方法)代替 StuInfor 里的所有“变量”(忧伤成河有提到),就如下面的 StuInfor 那样。
StuInfor 之后的 Student 类以典型的格式实现了 StuInfor。
interface StuInfor {
//static int no = 20052359;
void setID(long id);
long getID();
//int year = 2005;
void setYear(int year);