关于JAVA中形参的详解

在JAVA中形式参数主要有基本类型,类名,抽象类名,接口名。下面我们来各自讲述。

1.基本类型 这个太简单不做简述。

2.类名

  类名:需要该类的对象

 1 class Student {
 2     public void study() {
 3         System.out.println("Good Good Study,Day Day Up");
 4     }
 5 }
 6 
 7 class StudentDemo {
 8     public void method(Student s) { //ss; ss = new Student();  Student s = new Student();
 9         s.study();
10     }
11 }
12 
13 class StudentTest {
14     public static void main(String[] args) {
15         //需求:我要测试Student类的study()方法
16         Student s = new Student();
17         s.study();
18         System.out.println("----------------");
19         
20         //需求2:我要测试StudentDemo类中的method()方法
21         StudentDemo sd = new StudentDemo();
22         Student ss = new Student();
23         sd.method(ss);
24         System.out.println("----------------");
25         
26         //匿名对象用法
27         new StudentDemo().method(new Student());
28     }
29 }

  3.抽象类名:需要该类的子类对象

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);
    }
}

4.接口名:需要该接口的实现类对象

和抽象类名很相似

 1 //定义一个爱好的接口
 2 interface Love {
 3     public abstract void love();
 4 }
 5 
 6 class LoveDemo {
 7     public void method(Love l) { //l; l = new Teacher();  Love l = new Teacher(); 多态
 8         l.love();
 9     }
10 }
11 
12 //定义具体类实现接口
13 class Teacher implements Love {
14     public void love() {
15         System.out.println("老师爱学生,爱Java,爱林青霞");
16     }
17 }
18 
19 class TeacherTest {
20     public static void main(String[] args) {
21         //需求:我要测试LoveDemo类中的love()方法
22         LoveDemo ld = new LoveDemo();
23         Love l = new Teacher();
24         ld.method(l);
25     }
26 }

 

posted @ 2015-06-05 16:14  宋小俊要加油  阅读(677)  评论(0编辑  收藏  举报