当前位置: 技术问答>java相关
怎么实现?内部类问题。附原码
来源: 互联网 发布时间:2015-01-24
本文导语: public class Test { String s1 = "keyi"; String s2 = "kao"; class Inner { String s2 = "ft"; Inner () { System.out.println("Inner s = " + s2); //1 ...
public class Test {
String s1 = "keyi";
String s2 = "kao";
class Inner {
String s2 = "ft";
Inner () {
System.out.println("Inner s = " + s2); //1
System.out.println("outer s = " + s1); //2
System.out.println("outer s = " + new Test().s2); //3
}
}
}
问, 怎样,把外部的s2打印出来,但不能重新new Test(),实现我第3个打印的功能,在内部类的同一位置。
String s1 = "keyi";
String s2 = "kao";
class Inner {
String s2 = "ft";
Inner () {
System.out.println("Inner s = " + s2); //1
System.out.println("outer s = " + s1); //2
System.out.println("outer s = " + new Test().s2); //3
}
}
}
问, 怎样,把外部的s2打印出来,但不能重新new Test(),实现我第3个打印的功能,在内部类的同一位置。
|
public class Test {
String s1 = "keyi";
String s2 = "kao";
class Inner {
String s2 = "ft";
Inner () {
System.out.println("Inner s = " + s2); //1
System.out.println("outer s = " + s1); //2
System.out.println("outer s = " + Test.this.s2); //3
}
}
public static void main(String args[])
{
Test t =new Test();
Inner tin =t.new Inner();
}
}
String s1 = "keyi";
String s2 = "kao";
class Inner {
String s2 = "ft";
Inner () {
System.out.println("Inner s = " + s2); //1
System.out.println("outer s = " + s1); //2
System.out.println("outer s = " + Test.this.s2); //3
}
}
public static void main(String args[])
{
Test t =new Test();
Inner tin =t.new Inner();
}
}
|
class Inner {
String s2 = "ft";
Inner (String test_s2) //参数为new Test().s2
{
System.out.println("Inner s = " + s2); //1
System.out.println("outer s = " + s1); //2
System.out.println("outer s = " + test_s2); //3
}
String s2 = "ft";
Inner (String test_s2) //参数为new Test().s2
{
System.out.println("Inner s = " + s2); //1
System.out.println("outer s = " + s1); //2
System.out.println("outer s = " + test_s2); //3
}
|
我的解答:
public class Testinner
{
public static String test = "test";
public static void main(String[] args)
{
new Testinner();
}
public Testinner()
{
new Inner();
}
class Inner
{
private String s1 = "ft";
public Inner()
{
System.out.println("Inner s = " + this.s1);
System.out.println("outer s = " + test);
}
}
}
public class Testinner
{
public static String test = "test";
public static void main(String[] args)
{
new Testinner();
}
public Testinner()
{
new Inner();
}
class Inner
{
private String s1 = "ft";
public Inner()
{
System.out.println("Inner s = " + this.s1);
System.out.println("outer s = " + test);
}
}
}