Java形参和返回值

类名作为形参和返回值

方法的形参是类名,其实需要的是方法的对象

方法的返回值是类名,其实返回的是该类的对象

public class cat {
    public void eat(){
        System.out.println("猫吃鱼");
    }

}


public class catoperate {
    public void eatoperate(cat c){//方法的形参是类名
        c.eat();
    }

    //带返回值的
    public cat getCat(){
        cat c = new cat();
        return c;//返回一个cat类型的对象
    }
}


public class catdemon {
    public static void main(String[] args){
        catoperate a = new catoperate();//创建操作类的对象
        cat c = new cat();//因为eatoperate是带参的方法,需要创建一个对象,然后放到括号里面

        a.eatoperate(c);


        cat c2 = a.getCat();//等价于cat c2 = new cat();
        c2.eat();
    }
}

抽象类名作为形参和返回值

利用多态

public class cat extends animal {
    @Override
    public void eat() {
        System.out.println("猫吃鱼");
    }
}

public abstract class animal {
    public abstract void eat();
}

public class animaloperate {
    public void eatoperate(animal c){
        c.eat();
    }
    public animal eat(){
        animal a = new cat();
        return a;
    }


}


public class test {
    public static void main(String[] args){
        animaloperate a = new animaloperate();//创建操作类对象
        animal c = new cat();//创建形参对象
        a.eatoperate(c);
        animal b = a.eat();//等同于new cat(); 相当于猫类的对象
        b.eat();

    }
}


接口作为形参和返回值

注意接口和抽象类都不能实例化,都需要通过多态来创建对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值