JAVA 子类与继承例题2

使用super调用父类的构造方法

class Student{
	int number;
	String name;
	Student(){
	}
	Student(int number,String name){
		this.number=number;
		this.name=name;
		System.out.println("我的名字是:"+name+"学号是:"+number);
	}
}
class UniverStudent extends Student{
	boolean 婚否;
	UniverStudent(int number,String name,boolean b){
		super(number,name);
		婚否=b;
		System.out.println("婚否="+婚否);
	}
}
public class exam {

	public static void main(String[] args) {
		UniverStudent zhang =new UniverStudent(9901,"何晓林",false);

	}

}


final关键字

class A{
	final double PI=3.1415926; //PI常量
	public double getArea(final double r){
		//r=r+1;  非法,不允许对final变量进行更新操作
		return PI*r*r;
	}
public final void speak(){
	System.out.println("您好,How' everything here?");
}
}
public  class exam {

	public static void main(String[] args) {
		A a=new A();
		System.out.println("面积:"+a.getArea(100));
        a.speak();
	}
}

对象的上转型对象

class 类人猿{
	void crySpeak(String s){
		System.out.println(s);
	}
}
class People extends 类人猿{
	void computer(int a,int b){
		int c=a*b;
		System.out.println(c);
	}
	void crySpeak(String s){
		System.out.println("***"+s+"***");
	}
}
public  class exam {

	public static void main(String[] args) {
		类人猿 monkey;
		People geng = new People();
		monkey =geng;//monkey是People对象geng的上转型对象
		monkey.crySpeak("I love this game");
		//同等于geng.crySpeak("I love this game");
		People people=(People)monkey; //把上转型对象强置转化为子类的对象
		people.computer(10, 10);
	}
}

继承与多态

class 动物{
	void cry(){
		
	}
}
class 狗 extends 动物{
	void cry(){
		System.out.println("汪汪汪....");
	}
}
class 猫 extends 动物{
	void cry(){
		System.out.println("喵喵喵....");
	}
}
public  class exam {

	public static void main(String[] args) {
	 动物 animal;
	 animal=new 狗();
	 animal.cry();
	 animal=new 猫();
	 animal.cry();
	}
}

abstract类和abstract方法

abstract class GirlFriend{  //抽象类,封装了两个行为标准
	abstract void speak();
	abstract void cooking();
}
class ChinaGirlFriend extends GirlFriend{
	void speak(){
		System.out.println("你好");
	}
	void cooking(){
		System.out.println("水煮鱼");
	}
}
class AmericanGirlFriend extends GirlFriend{
	void speak(){
		System.out.println("Hello");
	}
	void cooking(){
		System.out.println("roast beef");
	}
}
class Boy{
	GirlFriend friend;
	void setGirlfriend(GirlFriend f){
		friend=f;
	}
	void showGirlFriend(){
		friend.speak();
		friend.cooking();
	}
}
public  class exam {

	public static void main(String[] args) {
	 GirlFriend girl=new ChinaGirlFriend(); //girl是上转型对象
	 Boy boy=new Boy();
	 boy.setGirlfriend(girl);
	 boy.showGirlFriend();
	 girl=new AmericanGirlFriend(); //girl是上转型对象
	 boy.setGirlfriend(girl);
	 boy.showGirlFriend();
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值