package xxx;
public abstract class Shape {
public abstract void square();
public abstract void zhouchang();
}
package xxx;
public class Rectangle extends Shape {
int chang=8;
int kuan=6;
int square=chang*kuan;
int zhouchang=(chang+kuan)*2;
@Override
public void square() {
// TODO Auto-generated method stub
}
@Override
public void zhouchang() {
// TODO Auto-generated method stub
}
public void cal(){
System.out.println("矩形的面积为:"+square+" "+"周长为"+zhouchang);
}
}
package xxx;
public class Circle extends Shape {
double r=6.00;
double square=3.14*r*r;
double zhouchang=0.50*3.14*r;
@Override
public void square() {
// TODO Auto-generated method stub
}
@Override
public void zhouchang() {
// TODO Auto-generated method stub
}
public void cal(){
System.out.println("圆形的面积为:"+square+" "+"周长为"+zhouchang);
}
}
package xxx;
public class initail {
public static void main(String[] args) {
Shape obj1=new Circle();
Shape obj2=new Rectangle();
obj1.square();
obj1.zhouchang();
obj2.square();
obj2.zhouchang();
}
}
代码里面没用带继承的知识啊,在自动生成的方法里面没有方法体。
没有结果的原因是因为,你在子类中重新定义的新方法cal,而你创建的对象是由父类指向子类的,根本不能调用子类中的方法。
对于你的代码,你可以试试看创建子类对象,直接用子类对象调用方法
Circle circle=new Circle();
circle.cal();
Rectangle rectangle=new Rectangle();
rectangle.cal();
输出结果的方法是
public void cal(){
System.out.println("圆形的面积为:"+square+" "+"周长为"+zhouchang);
}
}
所以测试类中应该添加 obj1.cal(); obj2.cal();