Java 类方法和对象方法的区别

类方法和对象方法的区别

  • 类方法可以直接通过类名.方法名调用(在类被加载时,被一起加载)
  • 对象方法则需要先 new 一个对象,之后再通过对象.方法名调用
public class Demo03 {
    public static void main(String[] args) {

        //类方法
        int sum = add(10, 20);
        System.out.println(sum);

        //对象方法
        Demo03 demo03 = new Demo03();
        int max = demo03.max(10, 20);
        System.out.println(max);
    }

    public static int add(int a,int b){//类方法
        return a+b;
    }
    public int max(int num1,int num2){//对象方法
        int result = 0;

        if (num1==num2){
            System.out.println("num1=num2");
            return 0;//终止方法
        }
        if (num1>num2){
            result = num1;
        }else {
            result = num2;
        }
        return result;
    }
}
posted @ 2023-03-27 16:55  远帆启航  阅读(48)  评论(0)    收藏  举报