Java中的继承

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();
		
		
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值