方法参数类型以及返回值类型问题研究

方法参数类型以及返回值类型问题研究

  1. 类名作为形式参数
    以后如果你看的一个方法的形参要一个类,类型,那你就传递一个该类的对象
    案例演示
public class MyTest {
    public static void main(String[] args) {
        //以后如果你看的一个方法的形参要一个类,类型,那你就传递一个该类的对象
        Student student = new Student();
        show(new Student(), 20);
        student.setNum(40);
        System.out.println(student.num);//
    }

    public static void show(Student student, int num) {
        student.num = num;
    }
}

class Student {
    int num = 100;

    public void setNum(int num) {
        this.num = num;
    }
}
  1. 抽象类名作为形式参数
    如果你以后看的一个方法的形参,要一个抽象类 类型,你就传递一个该类的子类对象。
    案例演示
public class MyTest2 {
    public static void main(String[] args) {
        //如果你以后看的一个方法的形参,要一个抽象类 类型,你就传递一个该类的子类对象。
        BB bb = new BB();
        show(bb, 50);
        System.out.println(bb.num); //  20
        bb.aa();
    }

    public static void show(AA aa, int num) {
        aa.num = num;

    }
}

abstract class AA {
    int num = 100;

    public abstract void aa();
}

class BB extends AA {
    int num = 20;

    @Override
    public void aa() {
        System.out.println(super.num);//   50
    }
}
  1. 接口名作为形式参数
    如果你以后看到一个方法的形参,要一个接口类型,你就传一个该接口的子类对象。
    案例演示
public class MyTest {
    public static void main(String[] args) {
        //如果你以后看到一个方法的形参,要一个接口类型,你就传一个该接口的子类对象。
        MyClass myClass = new MyClass();
        show(myClass);
        myClass.setNum(500);
        System.out.println(myClass.num); //2. 500
        System.out.println(MyInterface.num); //3. 100
    }

    public static void show(MyInterface myInterface) { //MyInterface myInterface=myClass
        System.out.println(myInterface.num); //1. 100
    }
}

interface MyInterface {
    public static final int num = 100;

    void aa();
}

//ctrl+I 重写父接口的方法
//ctrl+O 重写父类的方法
class MyClass implements MyInterface {
    int num = 20;

    public void setNum(int num) {
        this.num = num;
    }

    @Override
    public void aa() {
        System.out.println(num);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值