java学习之继承与super关键字

本文探讨了Java编程中的继承概念及其在实际应用中的重要性,特别关注了super关键字的使用,如何通过super调用父类的构造器和方法。通过对实例代码car_box.java的分析,读者将能更深入地理解Java中的继承机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



//car_box.java

package package_two;

/** error:Implicit super constructor car() is undefined.
 *  Must explicitly invoke another constructor
 *  解决办法:在car class 中加入public car(){}
 * */

public class car_box extends car{
	
	int midu;
	
	public car_box(){System.out.println("car_box construct no.1");}
	
	public car_box(int width, int length, int weight, int high) {
		super( width, length, weight, high);//调用父类的构造函数,super必须放在首句
		System.out.println("car 的  width:");
		System.out.println("car 的  length:");
		System.out.println("car 的  weight:");
		System.out.println("car 的  high:");	
		System.out.println("car_box construct no.2");
	}
	
	public car_box(int midu){
		
		midu=midu;
		System.out.println("car_box 的 midu " + midu);
		System.out.println("car_box construct no.3");
	}
	
	public int thinks(){
		
		System.out.println("print thinks");
		return 0;
		
	}

}




//car.java

package package_two;

public class  car {
	int weight,high,length;
	int width;
	
	public car(){
		System.out.println("car construct null");
	}
	
	public car(int weight){
		weight=weight;
		System.out.println("car_wight:"+weight);
		System.out.println("car construct no.1");
	}
	
	public car(int high,int length){
		high=high;
		length=length;
		System.out.println("car_high" + high);
		System.out.println("car_length" + length);
		System.out.println("car construct no.2");
	}
	
	public car(int width, int length, int weight, int high){
		width = width;
		length = length;
		weight = weight;
		high = high;
		
		System.out.println("car_width=" + width);
		
		System.out.println("car_length=" + length);
		
		System.out.println("car_weight=" + weight);
		
		System.out.println("car_high="+high);
		
		System.out.println("car construct no.3");
	}
	
	public int car_thinks(){
		
		System.out.println("print car_thinks");
		
		return 0;
	}
	
}


//Test_class.java
package package_two;

/*补充知识: System.in.read()读入字符串
 * 			char ah;
 * 			while(true) {
 				try {
 				ah=(char)System.in.read();
 				System.out.println(ah);
 				}
 				catch(Exception e) {
 					e.getMessage();
 				}
 
 			}
 * 
 * */
public class Test_class {

	public static void main(String[] args) {
		
		car c = new car();
		
		car cc = new car(111,222);
		
		car ccc = new car(12,12,16,18);
		
		car_box cb = new car_box(1,2,3,4);
		
		car_box cbc = new car_box(100);
		
		c.car_thinks();
		
		cb.thinks();//子类继承父类thinks()方法
		
		cb.car_thinks();

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值