JAVA高级面向对象(三)

  1. 向上转型:子类——>父类
    对于向上转型,程序会自动完成
    父类  父类对象 = 子类实例;
  2. 向下转型   父类----------->子类
    子类  子类对象 =  (子类)父类实例;
  3. 多态应用的小例子
    package lianxijihe;
    class A{
    	public void fun1(){
    		System.out.println("AAA1111");
    	}
    	public void fun2(){
    		this.fun1();
    	}
    }
    class B extends A{
    	public void fun1(){
    		System.out.println("bbbbbbb");
    	}
    }
    class C extends A{
    	public void fun1(){
    		System.out.println("cccccccccc");
    	}
    }
    public class lianxi017 {
    	public static void main(String args[]){
    		fun(new B());
    		fun(new C());
    	}
    	public static void fun(A a){
    		a.fun1();
    	}
    }
    

  4. JAVA中可以使用instanceof 来判断一个对象到底是哪个类的实例。
  5. 再向下转型之前最好先用instanceof进行判断。
  6. 一个类永远不要去继承一个已经实现好的类。而只能继承抽象类和接口。
  7. 抽象类的实际应用-------模板设计
    代码如下:
    package lianxijihe;
    abstract class Persons{
    	private String name;
    	private int age;
    	
    	public Persons(String name,int age){
    		this.name = name;
    		this.age = age;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public int getAge() {
    		return age;
    	}
    
    	public void setAge(int age) {
    		this.age = age;
    	}
    	
    	public void say(){
    		System.out.println(this.getContent());
    	}
    	
    	public abstract String getContent();
    }
    class Students extends Persons{
    	private int score;
    	public Students(String name, int age,int score) {
    		super(name, age);
    		this.score = score;
    	}
    
    	@Override
    	public String getContent() {
    		return "姓名:"+super.getName()+",年龄:"+super.getAge()
    				+",分数:"+this.score;
    	}
    	
    }
    class Worker extends Persons{
    	private int salary;
    	public Worker(String name,int age,int salary){
    		super(name,age);
    		this.salary = salary;
    	}
    	public String getContent(){
    		return "姓名:"+super.getName()+",年龄:"+super.getAge()
    		+",分数:"+this.salary;
    	}
    }
    public class lianxi018 {
    	public static void main(String args[]){
    		Persons stu = new Students("梨花", 15, 100);
    		Persons wor = new Worker("王虎",25,4000);
    		stu.say();
    		wor.say();
    	}
    }
    

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值