首页 > 编程语言 > 详细

Java 方法与调用

时间:2021-04-08 18:08:52      阅读:31      评论:0      收藏:0      [点我收藏+]

Java 方法与调用

  • 方法定义

    /*
    修饰符  返回值类型 方法名(...){
        //方法体
        return 返回值;
    }
     */
    public String test(){
        return "hello";
    }
    
    public void test1(){
        return;
    }
    
    public int max(int a,int b){
        int c = a>b?1:0;
        return c;
    }
    
  • 静态方法调用

    public class Demo02 {
    
        public static void main(String[] args) {
            Student.say();
        }
        
    }
    
    public class Student {
    
        // 静态方法:static
        public static void say(){
            System.out.println("student is saying");
        }
    }
    
    //student is saying
    
  • 非静态方法调用

    public class Demo02 {
        public static void main(String[] args) {
            //实例化这个类
            Student student = new Student();
            student.say();
        }
    }
    
    public class Student {
        // 非静态方法
        public void say(){
            System.out.println("student is saying");
        }
    }
    //student is saying
    
  • static 方法是和类一起加载的,非静态方法是类实例化后才加载的。

  • Java 都是值传递

    public static void main(String[] args) {
        int a  = 1;
        change(a);
        System.out.println(a);
    }
    
    //无返回值
    public static void change(int a){
       a = 10;
    }
    
    //1
    
  • 引用传递

    public class Demo04 {
        //引用传递:对象,本质还是值传递
        public static void main(String[] args) {
            Person person = new Person();
            System.out.println(person.name);
    
            Demo04.change(person);
            System.out.println(person.name);
        }
    
        public static void change(Person person){
            person.name = "张三";
        }
    }
    
    //定义一个Person类,属性name
    class Person{
        String name;
    }
    
    //null
    张三
    

Java 方法与调用

原文:https://www.cnblogs.com/saxonsong/p/14633148.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!