class Outer{
private String info="hello world!";
public void fun(){
new Inner(this).print();
}
public String getInfo(){
return this.info;
}
}
class Inner{
private Outer out=null;
public Inner(Outer out){
this.out=out;
}
public void print(){
System.out.println(this.out.getInfo());
}
}
public class JavaDemo03{
public static void main(String args[]){
new Outer().fun();
}
} new Outer().fun()调用Outer类中的fun()方法,再从new Inner(this)实例化调用Inner类中的print()方法,而在Inner类中为了能访问Outer类中被封装的info属性,必须实例化Outer对象。各位觉得我分析的对吗? 但是当前对象new Outer()是怎么传递进去的呢?先传到new Inner(this)中,再传到this.out中。总觉得new Inner(this)代码无法理解,还有不能用this.getInfo(),传入的不是new Outer()吗?this.out=out中的this具体是指什么呢?各位高手相助啊,谢谢啊O(∩_∩)O~
private String info="hello world!";
public void fun(){
new Inner(this).print();
}
public String getInfo(){
return this.info;
}
}
class Inner{
private Outer out=null;
public Inner(Outer out){
this.out=out;
}
public void print(){
System.out.println(this.out.getInfo());
}
}
public class JavaDemo03{
public static void main(String args[]){
new Outer().fun();
}
} new Outer().fun()调用Outer类中的fun()方法,再从new Inner(this)实例化调用Inner类中的print()方法,而在Inner类中为了能访问Outer类中被封装的info属性,必须实例化Outer对象。各位觉得我分析的对吗? 但是当前对象new Outer()是怎么传递进去的呢?先传到new Inner(this)中,再传到this.out中。总觉得new Inner(this)代码无法理解,还有不能用this.getInfo(),传入的不是new Outer()吗?this.out=out中的this具体是指什么呢?各位高手相助啊,谢谢啊O(∩_∩)O~
this指的是当前对象也就是Inner的实例。
private String info="hello world!"; public String getInfo(){
Outer outer = this;
return outer.info;
}
}
public class JavaDemo03{
public static void main(String args[]){
Outer outer = new Outer();
System.out.println(outer.getInfo());
}
}
首先可以将Outer对象作为另一个代理对象(类型为Inner)的成员变量,通过调用Inner对象的方法(print)来间接调用Outer对象的方法(getInfo)。如:class Outer{
private String info="hello world!"; public String getInfo(){
Outer outer = this;
return outer.info;
}
}
class Inner{
private Outer out=null; public Inner(Outer out){
// 这里没有创建新的Outer对象
Inner inner = this;
inner.out=out;
} public void print(){
Inner inner = this;
Outer outer = inner.out;
System.out.println(outer.getInfo());
}
}
public class JavaDemo03{
public static void main(String args[]){
// Outer对象只在这里被创建了一次
Outer outer = new Outer();
Inner inner = new Inner(outer);
inner.print();
}
}
但是楼主还闲不够烦,又要由Outer对象负责Inner对象的创建过程。如:class Outer{
private String info="hello world!"; public String getInfo(){
Outer outer = this;
return outer.info;
} public void fun(){
Outer outer = this;
Inner inner = new Inner(outer);
inner.print();
}
}
class Inner{
private Outer out=null; public Inner(Outer out){
// 这里没有创建新的Outer对象
Inner inner = this;
inner.out=out;
} public void print(){
Inner inner = this;
Outer outer = inner.out;
System.out.println(outer.getInfo());
}
}
public class JavaDemo03{
public static void main(String args[]){
// Outer对象只在这里被创建了一次
Outer outer = new Outer();
outer.fun();
}
}
事实上,楼主在这里要掌握的是this关键字的用法,关于这一点,可以看一看Java的基本语法书,也可以看一看ZangXT对this的描述。
2,因为this是Inner对象 所以没法用this.getInfo() 必须用this.out.getInfo()
3,this.out=out this是Inner对象