1、类名作为方法的形参
方法的形参是类名,其实需要的是该类的对象
实际传递的是该对象的【地址值】
2、类名作为方法的返回值
方法的返回值是类名,其实返回的是该类的对象
实际传递的,也是该对象的【地址值】
示例代码:
class Cat {
public void eat() {
System.out.println("猫吃鱼")?
}
}
class CatOperator {
public void useCat(Cat c) { //Cat c = new Cat()?
c.eat()?
} p
ublic 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()? //new Cat()
c2.eat()?
}
}
示例代码:
abstract class Animal {
public abstract void eat()?
}
class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫吃鱼")?
}
}
class AnimalOperator {
public void useAnimal(Animal a) { //Animal a = new Cat()?
a.eat()?
}
public Animal getAnimal() {
Animal a = new Cat()?
return a?
}
}
public class AnimalDemo {
public static void main(String[] args) {
//创建操作类对象,并调用方法
AnimalOperator ao = new AnimalOperator()?
Animal a = new Cat()?
ao.useAnimal(a)?
Animal a2 = ao.getAnimal()? //new Cat()
a2.eat()?
}
}
接口作为形参和返回值
示例代码:
public interface Jumpping {
void jump()?
}
class JumppingOperator {
public void useJumpping(Jumpping j) { //Jumpping j = new Cat()?
j.jump()?
}
public Jumpping getJumpping() {
Jumpping j = new Cat()?
return j?
}
}
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()? //new Cat()
j2.jump()?
}
}
原文:https://www.cnblogs.com/zjh1170/p/15312336.html