1.Shap
package com.yfs.javase; public class Shape /*extends Object */{ //默认继承object object方法全部继承 //计算面积方法 public double getArea() {//代码完全没用 System.out.println("计算面积"); return 0; } }
2.Circle
package com.yfs.javase; public class Circle extends Shape { private double r; public Circle(double r) { this.r = r; System.out.println("创建圆形面积"); } // public double getArea() {//覆盖父类的方法 // System.out.println("计算圆形面积..."); // return 3.14 * r * r; // } }
3.Triangle
package com.yfs.javase; public class Triangle extends Shape { private double height; private double width; public Triangle(double height, double width) { this.height = height; this.width = width; System.out.println("创建三角形面积"); } public double getArea() { System.out.println("计算三角形面积..."); return 1.0 / 2 * width * height; } }
4.Rectangle
package com.yfs.javase; public class Rectangle extends Shape { private double width; private double length; public Rectangle(double width, double length) { this.width = width; this.length = length; System.out.println("创建矩形面积"); } public double getArea() { System.out.println("计算矩形面积..."); return width * length; } }
5.shap测试
package com.yfs.javase; public class ShapeTest { public static void main(String[] args) { Shape[] shapes = new Shape[10]; Shape s = new Shape();//创建这个类对象 s.getArea(); } }
6.抽象类
package com.yfs.javase; //类中有抽象方法 类必须是抽象的 public abstract class Demo1 { public abstract void method(); //没有方法体 抽象方法 public abstract double method1(int a, String name); public abstract double method1(String name,int a); //抽象类可以声明普通方法 子类可以继承 public void method2() { System.out.println("call method2()... "); } //普通方法是否可调用抽象方法 public void method3() { method();//不会调用父类的方法 调用子类对象的方法 多态 } } abstract class Child extends Demo1 { @Override public void method() { System.out.println("call () ......."); } } class Son extends Child { @Override public double method1(int a, String name) { // TODO Auto-generated method stub return 0; } @Override public double method1(String name, int a) { // TODO Auto-generated method stub return 0; } } class Children extends Demo1 { //子类继承抽象类 必须覆盖抽象方法 @Override public void method() { System.out.println("子类覆盖的抽象方法..."); } @Override public double method1(int a, String name) { System.out.println("name = " + name); System.out.println("a = " + a); return 0; } @Override public double method1(String name, int a) { // TODO Auto-generated method stub return 0; } public static Demo1 test (Demo1 d) { return new Children(); } }
7.抽象类测试
package com.yfs.javase; public class Demo1Test { /** * 1.抽象类不能实例化 * 2.子类必须覆盖抽象类的抽象方法 */ public static void main(String[] args) { Demo1 d1;//声明引用 //创建对象 //d1 = new Demo1();//抽象类不能实例化 d1 = new Children(); d1.method(); d1.method2(); Children c1 = new Children(); c1.method2(); System.out.println("============================"); d1.method3(); c1.method3(); d1.method1(15, "影分身"); Demo1 d2 = Children.test(c1); Demo1 c2 = Children.test(d1); d2.method2(); c2.method2(); } }