jfj8848
2014-12-05 22:35
package com.imooc; public abstract class Sharp { abstract void circumference(); abstract void area(); }
package com.imooc; public class Rectangle extends Sharp { public double length = 5; public double width = 3; void circumference() { // TODO Auto-generated method stub double getCircumference = 2 * (length + width); System.out.println("长方形周长:" + getCircumference); } void area() { // TODO Auto-generated method stub double getArea = length * width; System.out.println("长方形面积:" + getArea); } }
package com.imooc; public class Circle extends Sharp { final float pi = 3.14f; double r = 3; void circumference() { // TODO Auto-generated method stub double getCircumference = 2 * r * pi; System.out.println("圆周长:" + getCircumference); } void area() { // TODO Auto-generated method stub double getArea = r * r * pi; System.out.println("圆面积:" + getArea); } }
package com.imooc; public class InitialSharp { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Rectangle tu01 = new Rectangle(); tu01.length = 2; tu01.width = 3; tu01.area(); Circle tu02 = new Circle(); tu02.circumference(); } }
属性写成private类型
给每一个子类写有参构造方法,这样在创建子类对象时可以调用有参构造方法传进参数。
首先重写子类的方法必须和被继承的父类的方法相同
//父类
public class Shape {
public void getArea(){
System.out.println("图形的面积");
}
public void getGirth(){
System.out.println("图形的周长");
}
}
//圆形子类
public class Circle extends Shape {
int r=3;
public void getArea(){
double area=3.14*r*r;
System.out.println("圆形的面积"+area);
}
public void getGirth(){
double girth=2*3.14*r;
System.out.println("圆形的周长"+girth);
}
}
//方形子类
public class Rectangle extends Shape {
int a=2;
int b=4;
public void getArea(){
double area=a*b;
System.out.println("方形的面积"+area);
}
public void getGirth(){
double girth=2*(a+b);
System.out.println("圆形的周长"+girth);
}
}
//测试类
public class Initial {
public static void main(String[] args) {
// TODO Auto-generated method stub
Circle circle= new Circle();
circle.getArea();
circle.getGirth();
Rectangle rectangle= new Rectangle();
rectangle.getArea();
rectangle.getGirth();
}
}
创建对象可以用多态的方法创建对象吧
这就是继承的体现,那么现在再有个图形,同时具有周长,面积和特殊的性质,那么这里只要继承,重写方法后,再写自己特殊的性质就可以了
Java入门第二季 升级版
530715 学习 · 6091 问题
相似问题