public abstract class TuAn { abstract void zhouchang(); abstract void mianji(); }
这是抽象类;
public class FangXing extends TuAn { public int a; public int b; public void setA(int a) { this.a = a; System.out.println("a=" + a); } public void setB(int b) { this.b = b; System.out.println("b=" + b); } @Override void zhouchang() { // TODO Auto-generated method stub System.out.println("a=" + a); System.out.println("b=" + b); System.out.println((2 * (a + b))); } @Override void mianji() { // TODO Auto-generated method stub System.out.println(a * b); } }
这是方形。。;
public class YuanXing extends TuAn { int r; void zhouchang() { // TODO Auto-generated method stub System.out.println(2 * 3.14 * r); } @Override void mianji() { // TODO Auto-generated method stub System.out.println(3.14 * r * r); } public void setR(int r) { this.r = r; } }
这是圆形;
import java.util.Scanner; public class Initial1 { public static void main(String[] args) { // TODO Auto-generated method stub TuAn tuan1 = new FangXing(); TuAn tuan2 = new YuanXing(); Scanner scr = new Scanner(System.in); FangXing a = new FangXing(); YuanXing b = new YuanXing(); a.setA(scr.nextInt()); a.setB(scr.nextInt()); tuan1.zhouchang(); tuan1.mianji(); b.setR(scr.nextInt()); tuan2.zhouchang(); tuan2.mianji(); scr.close(); } }
这是测试类 ;
问题是运行的时候参数读不进去啊。。。求指点;
你把tuan1换成a tuan2换成b试一下 你传的参数是给a,和b对象的,tuan1和tuan2这两个对象并没有传参数。
我觉得这个时候你不要用多态了,TuAn tuan1,而是用子类引用指向子类对象,这样应该没问题,如果有问题你再问我