栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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
转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1038032.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号