类名作为形参和返回值

类名作为形参

其实要的是该类的对象

  1. public class Cat {
  2. public void eat(){
  3. System.out.println("cat eat fish");
  4. }
  5. }
  1. /*
  2. 测试类
  3. */
  4. public class CatDemo {
  5. public static void main(String[] args) {
  6. CatOperator co = new CatOperator();
  7. Cat c = new Cat();
  8. co.useCat(c);
  9. }
  10. }
  1. public class CatOperator {
  2. public void useCat(Cat c){ //Cat c = new Cat();
  3. c.eat();
  4. }
  5. }

类名作为返回值

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

  1. public class Cat {
  2. public void eat(){
  3. System.out.println("cat eat fish");
  4. }
  5. }
  1. /*
  2. 测试类
  3. */
  4. public class CatDemo {
  5. public static void main(String[] args) {
  6. CatOperator co = new CatOperator();
  7. Cat c = new Cat();
  8. co.useCat(c);
  9. Cat c2 = co.getCat(); //new Cat()
  10. c2.eat();
  11. }
  12. }
  1. public class CatOperator {
  2. public void useCat(Cat c){ //Cat c = new Cat();
  3. c.eat();
  4. }
  5. public Cat getCat(){
  6. Cat c = new Cat();
  7. return (c);
  8. }
  9. }

image.png

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

  1. public abstract class Animal {
  2. public abstract void eat();
  3. }
  1. public class AnimalDemo {
  2. public static void main(String[] args){
  3. AnimalOperator ao = new AnimalOperator();
  4. Animal a= new Cat();
  5. ao.useAnimal(a);
  6. Animal a2 = ao.getAnimal(); //new Cat();
  7. a2.eat();
  8. }
  9. }
  1. public class Cat extends Animal{
  2. public void eat(){
  3. System.out.println("猫吃鱼");
  4. }
  5. }
  1. public class AnimalOperator {
  2. public void useAnimal(Animal a){ //Animal a= new Cat();
  3. a.eat();
  4. }
  5. public Animal getAnimal() {
  6. Animal a = new Cat();
  7. return a;
  8. }
  9. }

image.png

接口名作为形参和返回值

image.png
image.pngimage.pngimage.png
image.png