java函数

java里面的函数分为普通函数和构造函数,构造函数又分为无参构造函数和有参构造函数,构造方法主要用于创建对象和初始化。函数如果有返回值,需要定义返回值类型。如果函数不需要返回值,则需要用void关键字来声明。调用的时候,通过new关键字,创建对象调用。

普通函数:

package com.mg.java.day05;

public class Test01 {
    
    // 没有返回值的函数
    public void sendMsg(String name) {
        System.out.println(name + "你在做什么?");
    }

    // 有返回值的函数
    public String get_grade(int score) {
        if (score < 60) {
            return "考试未及格";
        } else if (score >= 60 && score < 80) {
            return "成绩一般,继续努力";
        } else {
            return "优秀";
        }
    }

    public static void main(String[] args) {
        Test01 student = new Test01(); // TODO 创建一个学生对象
        String result = student.get_grade(89);
        System.out.println(result);

        student.sendMsg("小明");
    }
}

构造函数:

package com.mg.java.day05;

public class MobilePhone {
String brand;
int price;
String generation;

public void sendMsg(String name) {
System.out.println(name + "晚上一起吃饭吗?");
System.out.println("来自" + this.brand + this.generation + "价格" + this.price);
}

// 无参构造函数
public MobilePhone() {

}

// 有参构造函数
public MobilePhone(String brand, int price, String generation) {
this.brand = brand;
this.price = price;
this.generation = generation;
}

public static void main(String[] args) {
MobilePhone mobilePhone = new MobilePhone();
String name = "小华";
mobilePhone.sendMsg(name);

MobilePhone mobilePhone2 = new MobilePhone("苹果", 8888, "8P");
mobilePhone2.sendMsg("小明");

}
}

原文地址:https://www.cnblogs.com/xiamaojjie/p/12185291.html