Java方法之间的调用
- 1. 静态方法
- 1.1 静态方法调用静态方法
- 1.2 静态方法调用非静态方法
- 2. 非静态方法
- 2.1 非静态方法调用静态方法
- 2.2 非静态方法调用非静态方法
1. 静态方法
1.1 静态方法调用静态方法
package com.wang03.test;public class Test{public static void main(String[] args) {//同一个类,静态方法直接调用静态方法son1();System.out.println("=============");//不同类,静态方法通过:类名.方法名,调用静态方法son.son2();}//静态方法,子1public static void son1(){System.out.println("静态方法,子1");}
}
package com.wang03.test;public class Son {public static void son2(){System.out.println("静态方法,子2");}
}
1.2 静态方法调用非静态方法
同一个类中,或者不同类中,都是通过对象调用。
package com.wang03.test02;public class Test {public static void main(String[] args) {Test test = new Test();//同一类,静态方法通过对象调用非静态方法test.son1();System.out.println("==============");Son son = new Son();//不同类,静态方法也是通过对象调用非静态方法son.son2();}//非静态方法1public void son1(){System.out.println("非静态方法,子1");}
}
package com.wang03.test02;public class Son {//非静态方法2public void son2(){System.out.println("非静态方法,子2");}
}
2. 非静态方法
2.1 非静态方法调用静态方法
package com.wang03.test03;public class Test {public void father(){//同一个类,非静态方法直接调用静态方法son1();System.out.println("==========");//不同类,通过类名直接调用Son.son2();}//静态方法1public static void son1(){System.out.println("静态方法1");}public static void main(String[] args) {new Test().father();}
}
package com.wang03.test03;public class Son {//静态方法,子2public static void son2(){System.out.println("静态方法2");}
}
2.2 非静态方法调用非静态方法
package com.wang03.test04;public class Test {public void father(){//同一个类,直接调用son1();System.out.println("===========");//不同类,使用对象调用Son son = new Son();son.son2();}//非静态方法,子1public void son1(){System.out.println("非静态方法,子1");}public static void main(String[] args) {Test test = new Test();test.father();}
}
package com.wang03.test04;public class Son {//非静态方法,子2public void son2(){System.out.println("非静态方法,子2");}
}
如果有不对的地方,请大佬们多多指教!!!