package java_5_14;
/**
*
* @Description:
* @Author: Rainbow
* @version:v1.0
* @date:2021年5月14日下午9:54:51
*
*java 通过允许在一个类的说明中加入另一个类实现继承。
*继承:子类继承父类,被继承类也称为超类,继承类也称为子类。关键词:extends
*继承一个类并不会超越private 访问限制。
*Java程序员通常使用访问器方法来访问类的私有成员。
*声明private 的两个原则:
*1.实例变量只被它所在的类中方法使用。
*2.实例变量必须在一定的范围之内,为了防止无效赋值,只能通过访问器方法来访问。
* 那就应该将其声明为private。
* 在多层次的超类和子类的继承中,构成多层次结构。其中super的特性:
* super()的特性:总是引用最靠近的超类(继承上一级的类)的构造函数。
*/
//A class for two-dimensional object
class TwoDShape{
double width;
double heith;
private int sign1;
TwoDShape(){
heith=width=0.0;
}
TwoDShape(double w,double h){
width=w;
heith=h;
}
void showDim() {
System.out.println("width and heith: "+width+" and "+heith);
}
}
class Triangle extends TwoDShape{ //triangle 继承了 twodshape
String style;
Triangle(){
super();
style="no";
}
Triangle(String s,double w,double h){
super(w,h); //使用super 调用超类的构造函数。
style=s;
}
double area() {
return width*heith/2;
}
void showStyle() {
System.out.println("Trangle is "+style);
}
}
public class extend {
public static void main(String[] args) {
Triangle T1=new Triangle();
Triangle T2=new Triangle();
Triangle T3=new Triangle("aba",10.1,20.2);
T1.width=4.0;
T1.heith=4.0;
// T1.sign1=1; //Error:The field TwoDShape.sign1 is not visible
// 子类不能访问父类的私有权限类容,类外任何代码和子类都无权访问私有成员。
T1.style="filled!";
T2.heith=8.0;
T2.width=8.0;
T2.style="outlined!";
System.out.println("Info for t1: ");
T1.showStyle();
T1.showDim();
System.out.println("Area is "+T1.area());
System.out.println();
System.out.println("Info for t2: ");
T2.showStyle();
T2.showDim();
System.out.println("Area is "+T2.area());
System.out.println();
T3.area();
T3.showStyle();
System.out.println("area is "+T3.area());
//超类(父类)也可以单独使用
TwoDShape shape=new TwoDShape();
shape.heith=10.0;
shape.width=10.0;
shape.showDim();
}
}
Java中的继承
最新推荐文章于 2024-07-22 14:15:06 发布