一)抽象类的使用
2.编程技巧
(1) 抽象类定义的方法在具体类要实现;
(2) 使用抽象类的引用变量可引用子类的对象;
(3) 通过父类引用子类对象,通过该引用访问对象方法时实际用的是子类的方法。可将所有对象存入到父类定义的数组中。
package persons; public abstract class Shape { public abstract float getArea(); } public class Circle extends Shape { private float r; public Circle(float r) { this.setR(r); } public float getR() { return r; } public void setR(float r) { this.r=r; } public float getArea() { return (float)Math.PI*r*r; } } public class Triangle extends Shape { private float first; private float second; private float third; public Triangle(float first,float second,float third) { this.setFirst(first); this.setSecond(second); this.setThird(third); } public float getFirst() { return first; } public void setFirst(float f) { first=f; } public float getSecond() { return second; } public void setSecond(float s) { second=s; } public float getThird() { return third; } public void setThird(float t) { third=t; } public float getArea() { if(first+second>third&&first-second<third) { return (float)Math.sqrt((first+second+third)/2*((first+second+third)/2-third)*((first+second+third)/2-second)+(first+second+third)/2-first); } else { return 0; } } } public class Rectangle extends Shape { private float longs; private float wide; public Rectangle(float longs,float wide) { this.setLongs(longs); this.setWide(wide); } public float getLongs() { return longs; } public void setLongs(float l) { longs=l; } public float getWide() { return wide; } public void setWide(float w) { wide=w; } public float getArea() { return wide*longs; } } public class Calculations { public static void main(String[] args) { Circle c=new Circle(2); System.out.println(c.getArea()); Triangle t=new Triangle(5,4,3); System.out.println(t.getArea()); Rectangle r=new Rectangle(2,4); System.out.println(r.getArea()); } }

(二)使用接口技术
1定义接口Shape,其中包括一个方法size(),设计“直线”、“圆”、类实现Shape接口。分别创建一个“直线”、“圆”对象,将各类图形的大小输出。
(1) 接口中定义的方法在实现接口的具体类中要重写实现;
(2) 利用接口类型的变量可引用实现该接口的类创建的对象。
package pre; public interface Shape { public abstract float size(); } public class Circle implements Shape { private float r; public Circle(float r) { this.r=r; } public float getR() { return r; } public void setR(float r) { this.r=r; } public float size() { return (float)Math.PI*r*r; } } public class Straightline implements Shape { private float s; public Straightline(float s) { this.setS(s); } public float getS() { return s; } public void setS(float s) { this.s=s; } public float size() { return s; } } public class Area { public static void main(String[] args) { Straightline a=new Straightline(2); System.out.println(a.size()); Circle c=new Circle(2); System.out.println(c.size()); } }

学习总结:
1,object类:
object类是所有类的父类,如果一个类没有明显的继承一个类,则肯定是object的子类。
object类的主要方法:
1),public Object()
2),public boolean equals(Object obj) 作用:对象比较 (Object obj表示接受任意类型的数据,其中Object的数据类型为引用数据类型,equals方法比较的是地址不是内容)
3),public int hashCode() 作用:取得Hash码
4),public String toString() 作用:取得对象的内容
原文:https://www.cnblogs.com/chenqiang0630/p/11653526.html