总的来说,方法的调用主要有三种情况:
1.用对象引用调用类的实例方法
2.用类名直接调用静态方法(static修饰的方法)
3.类中的方法调用本类中的其他方法
首先,我们先来调用实例方法
package demo;
public class Welcome{
public static void main(String[] args)
{
//非静态方法,即实例方法的调用,要先定义一个类的对象
//然后再通过对象的引用调用方法
Calculation cal =new Calculation();
int sum =cal.cal01(5, 5);
System.out.println("The sum of the two numbers is :" + sum);
}
}
class Calculation{
public int cal01(int x ,int y){
return (x+y);
}
}
接下来,再看看调用静态方法
package demo;
public class Welcome{
public static void main(String[] args)
{
// Calculation cal =new Calculation();
// int sum =cal.cal01(5, 5);
int sum =Calculation.cal01(4, 5);
System.out.println("The sum of the two numbers is :" + sum);
}
}
class Calculation{
public static int cal01(int x ,int y){
return (x+y);
}
}
最后,我们来看看类中的方法的相互的调用
再同一类中的静态方法之间可以直接调用(即通过方法名直接调用)
package demo;
public class Welcome{
public static void main(String[] args)
{
// Calculation cal =new Calculation();
// int sum =cal.cal01(5, 5);
// int sum =Calculation.cal01(4, 5);
int sum =cal01(4,5);
System.out.println("The sum of the two numbers is :" + sum);
}
public static int cal01(int x ,int y){
return (x+y);
}
}
但是我们应该注意到,同一个类中,静态方法不能直接通过方法名来调用非静态方法
看下面的代码
package demo;
public class Welcome{
public static void main(String[] args)
{
// Calculation cal =new Calculation();
// int sum =cal.cal01(5, 5);
// int sum =Calculation.cal01(4, 5);
int sum =cal01(4,5);
System.out.println("The sum of the two numbers is :" + sum);
}
public int cal01(int x ,int y){
return (x+y);
}
}
会出现报错
所以,同一个类中,静态方法调用非静态方法也要通过对象来进行调用
就是调用自己的那个类来建立对象
package demo;
public class Welcome{
public static void main(String[] args)
{
Welcome ca = new Welcome();
int sum =ca.cal01(4, 5);
System.out.println("The sum of the two numbers is :" + sum);
}
public int cal01(int x ,int y){
return (x+y);
}
}
在同一类中,非静态方法可以直接调用静态方法与非静态方法。
如果不在一个类当中,静态方法调用其他类中的静态方法,必须通过类名+静态方法调用。
如果在不同包当中,静态方法调用其他类的非静态方法,需要导入该类中的包,以及通过创建对象调用。