java 继承的练习

继承练习

【1】查看下面代码的输出

ExtendsExercise01.java

public class ExtendsExercise01{
	public static void main(String[] args) {
		B a = new B();  
	}
}

class A{
	A(){ System.out.println("a");}
	A(String name){System.out.println("a");}}

class B extends A{
	B(){ this("abc");	// 调用了另一个构造器 B(String name)
		// 该构造器不存在有 super() 这是由于 this 和 super 不能同时存在
        System.out.println("b");}
	B(String name){ System.out.println("b name");}}
【输出】
a
b name
b

B() 中的 this("abc") 会调用 B(String name) 这个构造器,该构造器会首先 super() 调用父类的构造器,然后是 System.out.println("b"); ,B() 是没有 super() 的因为有一个 this() 了。


【2】查看下面代码的输出

ExtendsExercise02

public class ExtendsExercise02 {
	public static void main(String[] args) {
		C newc = new C();
	}
}

class A{ 
    public A(){ System.out.println("我是A类");} }

class B extends A{ 
    public B(){ System.out.println("我是B类的无参构造"); }
	public B(String name){ System.out.println(name + "我是B类有参构造器");}}

class C extends B{
	public C(){ this("hello"); System.out.println("我是C类的无参构造");}
	public C(String name){ super("haha"); System.out.println("我是C类的有参构造");}}
【输出】
我是A类
haha我是B类有参构造器
我是C类的有参构造
我是C类的无参构造

【3】编写一个继承的

  • 编写 Computer 类,包含CPU、内存、硬件等属性,getDetails 方法用于返回 Computer 的详细信息。
  • 编写 PC 子类,继承 Computer 类,添加特有属性【品牌 brand】。
  • 编写 Test 类,在 main 方法中创建 PC 和 NotePad 对象,分别给对象特有的属性。
  • 赋值,以及从 Computer 类中继承的属性赋值,并使用方法并打印输出信息。

Computer.java

public class Computer {
	private String cpu;
	private int memeory;
	private int disk;

	public Computer(String cpu, int memeory, int disk){
		this.cpu = cpu;
		this.memeory = memeory;
		this.disk = disk;
	}

	public String getDetails(){
		return "cpu=" + cpu + " memeory="+memeory +" disk="+disk;
	}

	public void setcpu(String cpu){
		this.cpu = cpu;
	}

	public String getcpu(){
		return cpu;
	}

	public void setmemeory(int memeory){
		this.memeory=memeory;
	}

	public int getmemory(){
		return memeory;
	}

	public void setdisk(int disk){
		this.disk = disk;
	}

	public int getdisk(){
		return disk;
	}
}

pc.java

public class pc extends Computer {
	private String brand;

	// 体现出继承的基本思想
	// 父类的构造器完成父类属性的初始化
	// 子类的构造器完成子类属性的初始化
	public pc(String cpu, int memeory, int disk, String brand){
		super(cpu, memeory, disk);
		this.brand = brand;
	}

	public void setbrand(String brand){
		this.brand = brand;
	}

	public String getbrand(){
		return brand;
	}

	// 
	public void printInofo(){
		System.out.print("PC的信息");
		System.out.print(getDetails()+" brand="+brand);
	}
}

test.java

public class test{
	public static void main(String[] args) {
		pc mypc = new pc("inter", 16, 500, "IBM");
		mypc.printInofo();
	}
}
posted @ 2024-05-07 14:38  takenika  阅读(11)  评论(0)    收藏  举报