那为什么上述两段程序可以通过呢?class B 不是覆盖了class A的m()方法吗?
解决方案 »
- java基础知识。。。关于移位(不知道这样表达对不。。看题)
- 有关JPanel上再添加JMapPane的问题
- 哪有jrockit下载?
- 外国一家公司的一道超难推理面试题,如果你做对了,直接录取拿5K以上的工资不成问题!!!!!!
- 我是一个新手~~请教一个问题!!
- 往jtextpanel 添加一个下拉菜单的问题
- 一个小问题(关于xml文件的生成)
- 出现"Exception in thread "main" java.lang.NoClassDefFoundError: Student"错误,是什么原因?
- 用JBuilder7如何把一个project编译成exe文件???或可安装的程序???
- java并发编程实战中一个看不懂的地方
- 如何将 JRE 随程序一起发布 ?
- 请问如何安装JAVA编译器啊?
class base1{
private int i;
public void seti(){
set();
}
public int get(){
return i;
}
private void set(){
i=5;
}
}
public class Untitled1 extends base1{
private int i;
private void set(){
i=4;
}
public static void main(String[] args) {
Untitled1 u=new Untitled1();
base1 b=new base1();
b.seti();
u.seti();
// seti();
System.out.println("u.i="+u.i+"\nb.i=" +b.get());
}
}
the result is:
u.i=0
b.i=5could you tell me why?
en ,it is an interesting thing if someone could explain how it works for me,thanks.
程序确实能通过。但不算覆盖。
private方法对于派生类来说根本不存在(不可见),看都看不到何谈覆盖?他们只是名称一样的两个毫不相干的两个方法,只在各自的类里可见,把他们的名字改成不同也不会对程序产生任何影响。
static成员不依赖对象而存在,但说static不能继承恐怕不准确。用派生类也可以访问基类的static方法(当然要可见)。关于是不是覆盖,下面说明:class a {
void m(){
System.out.println("this is class a");
};
}class b extends a {
void m(){
System.out.println("this is class b");
};
}class text {
public static void main() {
a a1 = new b();
a1.m();
}结果:
this is class b
这是正常的覆盖行为。然后在两个m()前加上static再看一下结果,你会发现:
this is class a
静态方法的调用根本不取决于对象的实际类型,而只是声明的类型。
所以,这也不是覆盖。
顺便提一下,C#根本不让这样的代码编译。
C#只允许ACLASS.foo(),不允许aObject.foo().
使用Java的时候应该避免后者,一些代码分析工具
比如JTest会告诉你这类错误。
比如 aObject.foo() 或者 this.foo() 等.看看The Java Programming Language 3rd Edition中关于这一段的描述:
A static member may also be accessed via a reference to an object of that class, but this form should be AVOIDED as it gives the false impression that static field is a member of the object, not a member of the class.
It is the type of the reference, not the type of the object it refers to, that determines the class to look in for the static vaiable. The reference can even be NULL.其实有一些集成开发环境(比如IntelliJ-IDEA)已经在帮助我们解决这个问题.使用对象引用的静态域在其编译环境中是不允许的(或者是被警告的).
功欲善其事,必先利其器.采用一些方便的工具确实是有很大的好处的.