Java中的每个类都继承自j ava.lang.Object类。如果一个类在定义时没有指定继承关系,那么它的父类就是Object.
因此每个类都隐含 extends java.lang.Object
先写一个几何图形类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public class SimpleGeometricObject { //JAVA中所有类都继承自java.lang.Object类 private String color="white"; private boolean filled; private java.util.Date dateCreated; public SimpleGeometricObject(){ dateCreated=new java.util.Date(); } public SimpleGeometricObject(String color,boolean filled){ dateCreated=new java.util.Date(); this.color=color; this.filled=filled; } public String getColor(){ return color; } public void setColor(String color){ this.color=color; } public boolean isFilled(){ return filled; } public void setFilled(boolean filled){ this.filled=filled; } public java.util.Date getDateCreated(){ return dateCreated; } public String toString(){ return "created on "+dateCreated+"\ncolor: "+color+" and filled: "+filled; } } |
圆也是几何图形,因此继承上面SimpleGeometricObject类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import java.util.*; public class Circle extends SimpleGeometricObject{ private double radius; public Circle(){ } public Circle(double radius){ this.radius=radius; } public Circle(double radius,String color,boolean filled){ super(color,filled);//注意super构造时必须位于子类构造代码的第一行。 //setColor(color); //setFilled(filled); this.radius=radius; } public double getRadius(){ return radius; } public void setRadius(double radius){ this.radius=radius; } public double getArea(){ return radius*radius*Math.PI; } public double getDiameter(){ return 2*radius; } public double getPerimeter(){ return 2*radius*Math.PI; } public void printCircle(){ System.out.println("The circle is created "+getDateCreated()+" and the radius is "+radius); } //方法重写,要在Circle类中调用定义在SimpleGeometricObject中的toString()方法需要使用super.toString() @Override//重写标注可加可不加 public String toString(){ return super.toString()+"\nradius is "+radius; } } |
下面是多态:
多态即父类的对象可以用子类来替换
1 2 3 4 5 6 7 8 9 |
public class Polymorphism { //多态 public static void main(String[] args){ display(new Circle(1,"red",false)); } public static void display(SimpleGeometricObject object){ System.out.println("Created on "+object.getDateCreated()+".Color is "+object.getColor()); } } |
可以使用表达式obj instanceof class(对象名instanceof类名)测试一个对象是否是一个类的实例。
对象转换:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Casting { //对象转换 //JAVA中所有类都继承自java.lang.Object类 public static void main(String[] args){ Object o1=new Circle(1);//首先程序隐式转换将一个Circle对对象赋值给Object对象 display(o1); } public static void display(Object o){ if(o instanceof Circle){ System.out.println("The circle area is "+((Circle)o).getArea()); //这里用显式将Object对象转换为Circle对象 } else if(o instanceof Object){ System.out.println("ERROR!!"); } } } |