日期:2014-05-20  浏览次数:20733 次

如何在程序外部使用内部类
我写了这样一个程序
涂红部位是一个内部类Node
public class Chain {
public class Node {
private String data;
private Node next;
public Node(String str,Node n)
{
data=str;
next=n;
}

public Node (String str)
{
data=str;
}
}
private Node first=null; 
public void addFirst(Node n){
n.next=first;
first=n;
}
public int length(){
int count =0;
Node temp=first;
if(temp==null)
return 0;
else{
while(temp.next!=null)
count++;
return count;
}
}
public void add(Node n){
Node temp=first;
if(first==null)
first=n;
else{
String a=temp.data;
String b=n.data;
while(a.compareTo(b)<0)
temp=temp.next;
temp.next=n;
}
}
public void addIndex(int a,Node n){
Node temp=first;
if(first==null){
first=n;
}
else{
int count=0;
while(count<a){
temp=temp.next;
}
temp.next=n;
}
}
public void deleteIndex(int a){
if(first==null)
System.out.println("链表内内容为空!");
else{
Node temp=first;
Node temp2=first.next.next;
int count=0;
while(count<a-1)
temp=temp.next;
temp.next=temp2;
}
}
public Chain combine(Chain c){
Node temp1=this.first;
Node temp2=c.first;
Chain chain=new Chain();
if(temp1==null)
return c;
if(temp1!=null&&temp2!=null){
int i;
int l1=this.length();
int l2=c.length();
if(l1<=l2)
i=l1;
else
i=l2;
for(int count=1;count<=i;count++){
if(temp1.data.compareTo(temp2.data)<0){
chain.add(temp1);
temp1=temp1.next;
}
else{
chain.add(temp2);
temp2=temp2.next;
}
}
if(l1<l2){
int diff=l2-l1;
for(int n=1;n<=diff;n++){
chain.add(temp2);
temp2=temp2.next;
}
}
else
{
int diff=l1-l2;
for(int n=1;n<=diff;n++){
chain.add(temp1);
temp1=temp1.next;
}
}
return chain;
}
else
return this;
}
}
下面是一个驱动类
public class Test {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Chain chain1=new Chain();
chain1.add(new Node("student"));
chain1.add(new Node("teacher"));
}

}
我在用new Node时报错,我应该怎么办呢????

------解决方案--------------------
Node node = new Chain().new Node("");
------解决方案--------------------
chain1.add(chain1.new Node("student"));
chain1.add(chain1.new Node("teacher"));
------解决方案--------------------
探讨

Node node = new Chain().new Node("");

------解决方案--------------------
探讨
Node node = new Chain().new Node("");

------解决方案--------------------
楼上的方法虽然很好 但是通用性不高 如果内部类是private属性的估计那样就不行吧 所以用反射是比较通用的
------解决方案--------------------
恩,内部类不能直接用的
探讨

Node node = new Chain().new Node("");

------解决方案--------------------
可以在外部类的构造中直接new 内部类,如果直接在客户端使用内部类,就破坏了封装了。就如同上面
Node node = new Chain().new Node("");
 这样肯定破坏了封装了。