java高手请进
importjava.io.*;interfaceWorker{publicvoiddoSomeWork();}classPlumberimplementsWorker{...
import java.io.*;interface Worker{ public void doSomeWork(); }class Plumber implements Worker{ public void doSomeWork(){ System.out.println("水管工"); }class Carpenter implements Worker{ public void doSomeWork(){ System.out.println("木匠"); } class Aworker implements Worker{ public Worker worker; public Aworker(Worker worker){ this.worker= worker; } @Override public void doSomeWork() { // TODO Auto-generated method stub System.out.println("你好!"); worker.doSomeWork(); } } }}public class Test2 { public static void main(String[] args){ Plumber plumber= new Plumber(); Aworker aworker = new Aworker(plumber); aworker.doSomeWork(); }}eclipse的提示是要我新建一个Awork类,,,我新建以后确实没有问题了,这是为什么呢?,弄成下面这样就可以了。。为什么放在同一个java代码里不行
展开
4个回答
展开全部
你是在学习内部类的只是吧?你定义的这3个类的关系是Plumber有内部类Carpenter,Carpenter又有内部类Aworker。所以你声明Aworker的时候应该这样声明:
import java.io.*;
interface Worker {
public void doSomeWork();
}
class Plumber implements Worker {
public void doSomeWork() {
System.out.println("水管工");
}
class Carpenter implements Worker {
public void doSomeWork() {
System.out.println("木匠");
}
class Aworker implements Worker {
public Worker worker;
public Aworker(Worker worker) {
this.worker = worker;
}
@Override
public void doSomeWork() {
// TODO Auto-generated method stub
System.out.println("你好!");
worker.doSomeWork();
}
}
}
}
public class Test2 {
public static void main(String[] args) {
Plumber plumber = new Plumber();
Plumber.Carpenter carpenter = plumber.new Carpenter();
Plumber.Carpenter.Aworker aworker = carpenter.new Aworker(plumber);
aworker.doSomeWork();
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
你把Aworker放到Carpenter类里了,放到外面就可以了
class Carpenter implements Worker{
public void doSomeWork(){
System.out.println("木匠");
}
}
class Aworker implements Worker{
public Worker worker;
public Aworker(Worker worker){
this.worker= worker;
}
@Override
public void doSomeWork() {
// TODO Auto-generated method stub
System.out.println("你好!");
worker.doSomeWork();
}
}
class Carpenter implements Worker{
public void doSomeWork(){
System.out.println("木匠");
}
}
class Aworker implements Worker{
public Worker worker;
public Aworker(Worker worker){
this.worker= worker;
}
@Override
public void doSomeWork() {
// TODO Auto-generated method stub
System.out.println("你好!");
worker.doSomeWork();
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
一个java文件中 只能有一个 public 的class,接口类默认就是public
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
你把Aworker写到Carpenter类里面去了,成为了一个成员内部类,那么你在Main方法里能直接new它吗?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询