java 学习之方法调用

总的来说,方法的调用主要有三种情况:

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);
	}
}

在同一类中,非静态方法可以直接调用静态方法与非静态方法。

如果不在一个类当中,静态方法调用其他类中的静态方法,必须通过类名+静态方法调用。

如果在不同包当中,静态方法调用其他类的非静态方法,需要导入该类中的包,以及通过创建对象调用。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值