面向对象中的参数返回值的基本用法

1.数据的封装

//学生类
public class Student {
    //属性
    String name;
    String city;
    int age;
}
public class Test02 {
    public static void main(String[] args) {
        //通过Student类创建对象student
        Student student = new Student();
        student.name = "晓晓";
        student.city = "北京";
        student.age = 20;
        System.out.println(student.name);
        System.out.println(student.city);
        System.out.println(student.age);
    }
}

2.方法的封装

public class Student {
    public void m1() {
        System.out.println("hello");
    }
}
public class Test02 {
    public static void main(String[] args) {
        //创建对象
        Student student = new Student();
        //调用方法
        student.m1();
    }
}

3.比较两个数的大小,无参数的传递,无返回值

public class Student {
    public void m2() {
        int x = 1;
        int y = 2;
        if (x > y) {
            System.out.println(x);
        } else if (x == y) {
            System.out.println("=");
        } else {
            System.out.println(y);
        }
    }
}
public class Test02 {
    public static void main(String[] args) {
        Student student = new Student();
        student.m2();
    }
}

4.比较两个数的大小,有参数传递,无返回值

public class Student {
    public void m2(int x,int y) {
        if (x > y) {
            System.out.println(x);
        } else if (x == y) {
            System.out.println("=");
        } else {
            System.out.println(y);
        }
    }
}
public class Test02 {
    public static void main(String[] args) {
        Student student = new Student();
        student.m2(1,2);
    }
}

5.比较两个数的大小,有参数传递,有返回值

public class Student {
    public int m2(int x, int y) {
        if (x > y) {
            return x;
        } else {
            return y;
        }
    }
}
public class Test02 {
    public static void main(String[] args) {
        Student student = new Student();
        int x = student.m2(1, 2);
        System.out.println(x);
    }
}

6.返回三个中的最大值

public class Student {
    public int m2(int x, int y) {
        if (x > y) {
            return x;
        } else {
            return y;
        }
    }
}
public class Test02 {
    public static void main(String[] args) {
        Student student = new Student();
        int a = 1;
        int b = 2;
        int c = 3;
        int x = student.m2(a, b);
        x = student.m2(x, c);
        System.out.println(x);
    }
}

7.计算1+2+n的和

public class Doctor {
    public int m(int x) {
        int sum = 0;
        for (int i = 0; i <= x; i++) {
            sum += i;
        }
        return sum;
    }
}
public class Test02 {
    public static void main(String[] args) {
        Doctor doctor = new Doctor();
        int x = doctor.m(2);
        System.out.println(x);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值