Java基础(方法参数和方法的返回值)

1.方法参数

  • 类作为方法参数:传递的是该类的对象
  • 抽象类作为方法参数 :传递的是该抽象类的子类对象
  • 接口作为方法参数: 传递的是该接口的实现类对象

代码示例:

package day0526;
public class demo3 {
    public static void main(String[] args) {
         Student student=new Student();
         m1(student);
         Zi zi=new Zi();
         m2(zi);
         Ziinter ziinter=new Ziinter();
         m3(ziinter);
    }
    //普通类
    public static void m1(Student student){
        System.out.println(student.name);
    }
    //抽象类
    public static void m2(Abstractclass a){
        System.out.println(a.name);
    }
    //接口
    public static void m3(Inters inters){
        System.out.println(inters.name);
    }
}
class Student{
    String name="yyy";
}
abstract class Abstractclass{
    String name="wtc";
}
class Zi extends Abstractclass {
}
interface Inters{
    String name="yw";
}
class Ziinter implements Inters{

}

2.返回值

  • 普通类作为方法返回值:返回该类的对象
  • 抽象类作为方法返回值:返回该抽象类的子类对象
  • 接口作为方法返回值:返回该接口的实现类对象

代码示例:

package day0526;

public class demo4 {
    public static void main(String[] args) {
          Students a=m1();
        System.out.println(a.name);
    }
     //普通类
    public static Students m1(){
        Students s=new Students();
        return s;
    }
     //抽象类
    public static AbPerson m2(){
        AbPerson a=new PersonAb();
        return  a;
    }
    //接口
    public static Interfuction m3(){
        Interfuction i=new ZiImpl();
        return i;
    }
}
class Students{
    String name="yyy";
}
abstract  class  AbPerson{
    String name="wtc";
}
class PersonAb extends AbPerson{

}
interface Interfuction{
    String name="wy";
}
class ZiImpl implements Interfuction{

}
发布了75 篇原创文章 · 获赞 164 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_41679818/article/details/90611080