public class B extends A{
public static void main(String[] args) {
A a;
B b = new B();
b.fun1();
a = b;
a.fun1();
}
}
class A{
void fun1(){
System.out.println(fun2());
}
int fun2(){
return 123;
}
}
运行结果是啥?求详细解释,每一步的,包括this指的是啥。。。
你这里没有写this,
我可以单独跟你解释一下
this,在普通方法中指的是调用本方法的对象
在构造方法中指的是正要初始化的对象
this不能用于静态方法。
给你写一个demo
public class demo1{
private int math1 = 5;
public static void main(String args[]){
demo1 d = new demo1();
d.trest();
}
public void trest(){
Systme.out.println(this.math1); //输出得5
}
}
这个简单,关键是你哪部分不会?
在类A中,方法fun1调用自己的fun2,所以两次的结果都是“123”。
由于一个类中只能有一个声明公共(public)的类,所以this指代的是本类,也就是类B,类A是一个被修饰为默认的类,借用了C语言中的protect,我们认为它的访问修饰符为protect。
流程:代码先声明了类A和类B,由于类B继承自类A,所以它具有父类所有的属性和方法(当然,它可以拓展自己的属性和方法),b调用fun1的时候,也就调用了自己所继承下来的fun1方法,然后是将b赋值给a(值传递,传递了对象的内存地址<补充一句,java只有值传递>),a同样调用的是b的fun1方法
哥们希望能给分
class A{
void fun1(){
System.out.println(this.fun2());
}
int fun2(){
return 123;
}
}
public class B extends A{
int fun2(){
return 456;
}
public static void main(String[] args) {
A a;
B b = new B();
b.fun1();
a = b;
a.fun1();
}
}
那如果是这种情况呢?
一样的结果吧
两个123