Java 父类和子类

时间:2023-03-09 03:55:49
Java 父类和子类
 package chapter11;

 public class GeometricObject1 {
private String color="white";
private boolean filled;
private java.util.Date dateCreated; public GeometricObject1(){
dateCreated=new java.util.Date();
} public GeometricObject1(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;
} }

首先新建一个几何体类,作为父类,具有一般几何体的共性;

 package chapter11;

 public class Circle4 extends GeometricObject1 {
private double radius;
public Circle4(){ }
public Circle4(double radius){
this.radius=radius;
}
public Circle4(double radius,String color,boolean filled){
this.radius=radius;
setColor(color);
setFilled(filled);
} 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);
} }
 package chapter11;

 public class Rectangle1 extends GeometricObject1 {
private double width;
private double height; public Rectangle1(){ }
public Rectangle1(double width,double height){
this.width=width;
this.height=height;
}
public Rectangle1(double width,double height,String color,boolean filled){
this.width=width;
this.height=height;
setColor(color);
setFilled(filled);
} public double getWidth(){
return width;
}
public void setWidth(double width){
this.width=width;
} public double getHeight(){
return height;
}
public void setHeight(double height){
this.height=height;
} public double getArea(){
return width*height;
}
public double getPerimeter(){
return 2*(width+height);
} }

然后建立了基于父类的两个子类,Circle和Rectangle类,分别具有自己的数据域和方法属性,并实现。

 package chapter11;

 public class TestCircleRectangle {

     public static void main(String[] args) {
// TODO Auto-generated method stub
Circle4 circle=new Circle4(1);
System.out.println("A circle "+circle.toString());
System.out.println("The radius is "+circle.getRadius());
System.out.println("The area is "+circle.getArea());
System.out.println("The diameter is "+circle.getDiameter()); Rectangle1 rectangle=new Rectangle1(2,4);
System.out.println("\nA rectangle "+rectangle.toString()+"\nThe area is "+
rectangle.getArea()+"\nThe perimeter is "+rectangle.getPerimeter()); } }

这是对子类的测试。

总结:

1、子类并不是父类的一个子集,实际上,一个子类通常比它的父类包含更多的信息和方法。

2、父类中的私有数据域在该类之外不可访问,同样在子类中也不能直接使用,需要使用父类中的访问器/修改器来进行访问和修改。

3、在Java中,不允许多重继承,一个Java类只能直接继承自一个父类,这种限制称为单一继承。多重继承可以通过接口来实现。