Java方法回顾

方法的定义

修饰符

返回类型

package oop.Demo01;
//Demo01 类
public class Demo01 {
    //main 方法
    public static void main(String[] args) {

    }
    /*
    修饰符 返回值类型  方法名(。。。){
    //方法体
    return 返回值;
    }
     */
    //retrun 方法的结束语句
    public String sayHello() {
        return "Hello World";
    }
    public  void print(){
        return;
    }
    public int max(int a, int b) {
        return a > b ? a : b;//三元运算符
    }
}
  • break:跳出switch,结束循环和return的区别 return是方法里面最后一句结束语 后面如过还有语句将报错
  • 方法名:注意规范就行,保持驼峰原则,见名知意
  • 参数列表:(参数类型,参数名)

方法的调用

静态方法: 用static修饰

非静态方法 :无static

package oop.Demo01;

public class Demo02 {
    public static void main(String[] args) {
        //静态方法 static
        //实例化这个类 new
        //对象类型 对象名= 对象值;
        student student = new student();
        student.say();
    }
    //和类一起加载的
    public  static void a(){
        //b();
    }
    //类实例化,才存在
    public  void b(){
        a();
    }
}

形参和实参

package oop.Demo01;

public class Demo03 {
    public static void main(String[] args) {
        //实参和形参的类型一致
        int add = Demo03.add(3,5);//实参 实际传输数据
        System.out.println(add);
    }
    public static int add(int a, int b) {//形参  接收数据
        return a + b;
    }
}
  • 值传递和引用传递 值传递是传递值 而引用传递是传递的数值的地址
package oop.Demo01;

public class Demo02 {
    public static void main(String[] args) {
        //静态方法 static
        //实例化这个类 new
        //对象类型 对象名= 对象值;
        student student = new student();
        student.say();
    }
    //和类一起加载的
    public  static void a(){
        //b();
    }
    //类实例化,才存在
    public  void b(){
        a();
    }
}
package oop.Demo01;
//引用传递:对象,本质还是值传递
public class Demo05 {
    public static void main(String[] args) {
        Perosn perosn = new Perosn();
        System.out.println(perosn.name);//null
        Demo05.change(perosn);
        System.out.println(perosn.name);//人来人往
    }

    public static void change(Perosn perosn) {
        //person是一个对象:值向的------>Perosn perosn = new Perosn();这是一个具体的人,可以改变属性!
        perosn.name = "人来人往";
    }
}
//定义了一个person类,有一个属性:name
class Perosn {
    String name;
}

this关键字

this关键字代表当前创建的对象本身

你可能感兴趣的:(java,开发语言)