java 关于继承、多态的练习题

每个孩子都会犯错,父母根据孩子犯错的类型不一样,对错误进行处理,教育孩子。写出父母类,孩子类和错误类。(比如考试不及格----谈心(输出一句话) 偷东西----挨打)

菜鸟的尝试,如果有什么错误和不妥,欢迎指出。

Public class child{

}

Public class error1 extends child(
érror1(){
}

Void testFail(){

}

}

Public class error2 extends child(
érror2(){
}

Void steals(){

}

}

Public class parents{
parents(){

}

Public static void print(child error){
If(error instanceof error1){
Print("谈心")
}

If(error instanceof error2){
Print("挨打")
}
}

Public static void main (string[] args){
Parents parent= new parents();

Error errora1 = new error1();

Error errora2 = new error2();

Parent.print(errora1);

Parent.print(errora2);

}

大概就这样了,纯手机敲出来的,很多语法不对,
但是看下思路还是看出来的。
温馨提示:内容为网友见解,仅供参考
第1个回答  2012-03-30
@SuppressWarnings("serial")
public class ChildError extends Exception {

public final Child who;

public ChildError(Child child, String msg) {
super(msg);
this.who = child;
}

}

/**
* 不及格。
*/
@SuppressWarnings("serial")
public class FlunkError extends ChildError {

public FlunkError(Child child, String msg) {
super(child, msg);
}

}

/**
* 偷东西。
*/
@SuppressWarnings("serial")
public class StealError extends ChildError {

public StealError(Child child, String msg) {
super(child, msg);
}

}

public class Parent {

public void educate(ChildError error){
if(error instanceof FlunkError){
this.talk((FlunkError) error);
}else if(error instanceof StealError){
this.beat((StealError) error);
}
}

/**
* 谈心。
*/
public void talk(FlunkError error){
System.out.println("父母说:“没事的”。");
}

/**
* 打。
*/
public void beat(StealError error){
System.out.println("父母怒打。");
}

}

public class Child {

private Parent parent;

public Child(Parent parent) {
super();
this.parent = parent;
}

public Parent getParent() {
return this.parent;
}

/**
* 考试。
*/
public void takeExamination() throws FlunkError{
System.out.println("孩子去考试。");
throw new FlunkError(this, "孩子考试不及格!");
}

/**
* 购物。
*/
public void shopping() throws StealError{
System.out.println("孩子去购物。");
throw new StealError(this, "孩子偷东西!");
}

}

public class Test {

public static void main(String[] args) {
Child c = new Child( new Parent() );
try {
c.takeExamination();
} catch (ChildError e) {
c.getParent().educate(e);
}
try {
c.shopping();
} catch (ChildError e) {
c.getParent().educate(e);
}
}

}
相似回答