【Java -- 类/抽象类/接口作为形参和返回值】

类作为形参和返回值

类作为形参时,传入的需要是类的对象;类作为返回类型时,返回的也是类的对象
定义一个 Cat 类:

public class Cat {
	public void eat() {
		System.out.println("Cat is eating");
	}
}

定义测试类:

public class Demo {
	public static void main(String[] args) {
		
		// 实际传入 Cat 类的对象
		animalEat(new Cat());
		
		Cat cat = getCat();
		cat.eat();
	}
	
	// 方法形参为 Cat 类
	public static void animalEat(Cat cat) {
		cat.eat();
	}
	
	// 返回类型为 Cat 类型,实际返回 Cat 类的对象
	public static Cat getCat() {
		Cat cat = new Cat();
		return cat;
	}
	
}

输出:

Cat is eating
Cat is eating

抽象类作为形参和返回值

抽象类作为方法形参时,由于抽象类不能实例化,因此需要利用多态创建该抽象类的子类对象,将其子类对象作为参数传入方法;当以抽象类作为方法的返回类型时,实际返回的也是其子类对象

来看案例,对于抽象类 Animal:

public abstract class Animal {
	private int age;
	public abstract void eat();
}

创建两个子类 Cat 和 Dog:

public class Cat extends Animal{
	@Override
	public void eat() {
		System.out.println("Cat is eating");
	}
}
public class Dog extends Animal {
	@Override
	public void eat() {
		System.out.println("Dog is eating");
	}

在测试类中定义一个以抽象类 Animal 为形参的方法以及一个以 Animal 类作作为返回类型的方法:

public static void animalEat(Animal a) {
	a.eat();
}

public static Animal getAnimal() {
	Animal a = new Cat();
//	Cat a = new Cat();  也可以这样写
	return a;
}

测试代码:

public static void main(String[] args) {
	
	Animal ani = new Cat();
	animalEat(ani);
	
	Cat cat = new Cat();
	animalEat(cat);
	
	animalEat(new Cat());
	animalEat(new Dog());
	
	Animal a = getAnimal();
	a.eat();
}

运行结果:

Cat is eating
Cat is eating
Cat is eating
Dog is eating
Cat is eating

接口作为形参和返回值

类似于抽象类,接口也不能实例化,所以接口作为形参和返回值时传入的和接受的都是实现该接口的类的对象

定义接口 Climb 以及 Cat 类实现该接口:

public interface Climb {
	void climbing();
}
public class Cat implements Climb {
	public void climbing() {
		System.out.println("The cat can now climb");
	}
}

测试代码:

public class Demo {
	public static void main(String[] args) {
		Climb c = new Cat();
		catClimb(c);
		
		Cat cat = new Cat();
		catClimb(cat);
		
		catClimb(new Cat());
		
		Climb a = getClimbingAnimal();
		a.climbing();
	}
	
	public static void catClimb(Climb c) {
		c.climbing();;
	}
	
	public static Climb getClimbingAnimal() {
//		Climb c = new Cat(); 这样写也可以
		Cat c = new Cat();
		return c;
	}
	
}

运行结果:

The cat can now climb
The cat can now climb
The cat can now climb
The cat can now climb
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值