RT,我们平时在用继承类时,常常想为什么父类里的成员变量,为什么我非要覆盖。我专心扩展我的东西不是更简约吗?
class A{
int a=0;
int b=0;
String str="0";
String str2="0";
}
class B extends A{
int b=0;
String str="0";
{
a=114;
b=114;
str="213";
str2="213";
System.out.println("super.a="+super.a);
System.out.println("super.b="+super.b);
System.out.println("super.str="+super.str);
System.out.println("super.str2="+super.str2);
}
void f(A ad){
a=11;
b=11;
str="21";
str2="21";
System.out.println("super.a="+super.a);
System.out.println("super.b="+super.b);
System.out.println("super.str="+ad.str);
System.out.println("super.str2="+ad.str2);
}
}
public class Main {
public static void main(String[] args) {
B b=new B();
b.f(b);
}
}
在A中 在B中
int n / b.n实际使用的是super.n
int n int n b.n就是b.n
现在你要修改B.n,第一种情况实际更改的是super.n
第二种情况才是修改真正的B对象中的n
现在我用抽象类试一下,为了保证abastract里数据能调用,为它们加上static(但是注意抽象方法是用不了static,static声明的方法必须有方法体)
abstract class Fu{
static int a1=1;
static int a2=1;
static String b1="123";
static String b2="123";
}
class Zi extends Fu{
int a2=1;
String b2="123";
}
public class Test1 {
public static void main(String[] args) {
Zi z=new Zi();
z.a1=299;
z.a2=299;
z.b1="12345";
z.b2="12345";
System.out.println(Fu.a1);
System.out.println(z.a1);
System.out.println(Fu.b1);
System.out.println(z.b2);
}
}
输出结果为
299
299
12345
12345
可见也是成立的
—————————–一句话总结——————————-
对象的数据属性 直接使用的是 最近一次覆盖的地方和值!