Java——形参和返回值
不止Java
共 3154字,需浏览 7分钟
·
2021-07-08 11:15
目录
类名作为形参和返回值
/*
猫类
*/
public class Cat {
public void eat() {
System.out.println("猫吃鱼");
}
}
/*
猫的操作类
*/
public class CatOperator {
public void useCat(Cat c) {
c.eat();
}
public Cat getCat() {
Cat c = new Cat();
return c;
}
}
/*
测试类
*/
public class CatDemo {
public static void main(String[] args) {
//创建操作类对象,并调用方法
CatOperator co = new CatOperator();
Cat c = new Cat();
co.useCat(c);
Cat c2 = co.getCat();
c2.eat();
}
}
抽象类名作为形参和返回值
*
动物类
*/
public abstract class Animal {
public abstract void eat();
}
/*
动物操作类
*/
public class AnimalOperator {
public void useAnimal(Animal a) {
a.eat();
}
public Animal getAnimal() {
Animal a = new Cat();
return a;
}
}
/*
猫类
*/
public class Cat extends Animal{
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
/*
测试类
*/
public class AnimalDemo {
public static void main(String[] args){
//创建操作类对象,并调用方法
AnimalOperator ao = new AnimalOperator();
Animal a = new Cat();
ao.useAnimal(a);
Animal a2 = ao.getAnimal();
a2.eat();
}
}
接口名作为形参和返回值
/*
接口
*/
public interface Jumpping {
void jump();
}
/*
接口的操作类
*/
public class JumppingOperator {
public void useJumpping(Jumpping j){
j.jump();
}
public Jumpping getJumpping(){
Jumpping j = new Cat();
return j;
}
}
/*
猫类
*/
public class Cat implements Jumpping {
@Override
public void jump() {
System.out.println("猫捉老鼠");
}
}
*
测试类
*/
public class JumppingDemo {
public static void main(String[] args){
//创建操作类对象,并调用方法
JumppingOperator jo = new JumppingOperator();
Jumpping j = new Cat();
jo.useJumpping(j);
Jumpping j2 = jo.getJumpping();
j2.jump();
}
}
往期推荐
评论