形式参数(类名、抽象类名、接口作为形式参数)

ntechnologytr778 2023-12-29 阅读:9 评论:0
大家好,今天给大家分享形式参数,一起来看看吧。它们都是引用类型。 抽象类、接口都不能实例化。类名作形参:需要的是该类的对象抽象类名作形参:需要的是该抽象类的子类对象 (抽象类多态)接口作形参:需要的是该接口的实现类对象 (接口多态)1、类名...

大家好,今天给大家分享形式参数,一起来看看吧。

它们都是引用类型。

抽象类、接口都不能实例化。

  • 类名作形参:需要的是该类的对象
  • 抽象类名作形参:需要的是该抽象类的子类对象 (抽象类多态)
  • 接口作形参:需要的是该接口的实现类对象 (接口多态)

1、类名作形参

class Student {public void study() {System.out.println("Good Good Study,Day Day Up");}}class StudentDemo {public void method(Student s) { //ss; ss = new Student(); Student s = new Student();s.study();}}class StudentTest {public static void main(String[] args) {//需求:我要测试Student类的study()方法Student s = new Student();s.study();System.out.println("----------------");//需求2:我要测试StudentDemo类中的method()方法StudentDemo sd = new StudentDemo();Student ss = new Student();sd.method(ss);System.out.println("----------------");//匿名对象用法new StudentDemo().method(new Student());}}123456789101112131415161718192021222324252627282930

2、抽象类名作形参

abstract class Person {public abstract void study();}class PersonDemo {public void method(Person p) {//p; p = new Student(); Person p = new Student(); //多态p.study();}}//定义一个具体的学生类class Student extends Person {public void study() {System.out.println("Good Good Study,Day Day Up");}}class PersonTest {public static void main(String[] args) {//目前是没有办法的使用的//因为抽象类没有对应的具体类//那么,我们就应该先定义一个具体类//需求:我要使用PersonDemo类中的method()方法PersonDemo pd = new PersonDemo();Person p = new Student();pd.method(p);}}12345678910111213141516171819202122232425262728

3、接口作形式参数

interface Love{public abstract void love();}class LoveDemo{public void method(Love l){//l= new Teacher(); Love l= new Teacher(); 多态l.love();}}//定义具体类实现接口class Teacher implements Love{public void love(){System.out.println("老师爱下棋");}}class TeacherTest {public static void main(String[] args) {//需求:我要测试LoveDemo中的love()方法LoveDemo ld= new LoveDemo();Love l= new Teacher();ld.method(l);}}

以上就是形式参数的内容分享,希望对大家有用。

版权声明

本文仅代表作者观点,不代表百度立场。
本文系作者授权发表,未经许可,不得转载。

«    2024年3月    »
123
45678910
11121314151617
18192021222324
25262728293031
最近发布
热门文章