JAVA中的方法

类=属性(名词)+方法(动词);

1,方法的定义
public 返回类型 方法名(){
//方法体
}
(1)方法的返回类型
a,无返回类型(注意:不能有return):void
b,有返回类型(注意:方法体最终一定要return对应的值)
基本类型:int,double,char,boolean,float…
引用类型:String,数组,对象
c,如果方法需要返回多个值
返回数组
返回对象
public class A{
double height;
double weight;
}
public A getInfo(){
A a=new A();
a.height=2.5;
a.weight=3.7;
return a;
}
(2)方法名
a,Java标示符组成
b,小写开头,逢单词首字母大写 ---------驼峰
c,尽量避免关键字:length(),next(),main()…
d,见名知意:run(),sleep(),eat()…
(3)方法体:main方法中的代码
2,方法的调用:对象名.方法名();
(1)有返回值
返回类型 变量=对象名.方法名();
public int aa(){…}
main(){
int i=对象.aa();
}
(2)无返回值
对象名.方法名();
(3)在同一个类中方法的相互调用
如果是自定义的方法,直接相互调用 方法名();
如果main方法要调用自定义方法,通过:对象名.方法名();
(4)不同类中方法相互调用
对象名.方法名();
3,变量的作用域
(1)成员变量(属性):整个类 ,默认值
(2)局部变量(方法里):定义的方法 ,必须初始化。
4,带参数的方法
(1)定义方式:
public 返回类型 方法名(形式参数){
//方法体
}
形式参数格式:参数类型1 参数名称1,参数类型2 参数名称2,… 参数类型n 参数名称n
public void method(int x,int y,String str){

}

(2)调用方式
a,对象名.方法名(实际参数)
int i=1;
a.method(i,3,“hello”);
b,参数的类型、个数和顺序必须对应
a.method(3,“hello”); 错误
a.method(3,“hello”,4); 错误
5,方法的练习
(1)基本类型的参数
public void mehtod1(int a,String b,double c){

}

(2)引用类型的参数
public void method2(String[]array){

}
public void method3(User user){
	
}












String s="hello";
char c=s.charAt(3);

System.out.println("hello");

A{
	B b;
}
B{
	C c;
}

C{
	aa();
}

A a=new A();
a.b.c.aa();

常见错误1:
public int aa(){
for()/if(){
return 1;
}
}
常见错误2:
public int aa(){
return 1+2.0;
}
//正确
public double aa(){
return 3;
}
常见错误3:
public int aa(){
return 2;

}
常见错误4:
public int aa(){
return 1;
return 2;
}
常见错误5:
public int aa(){
return a,b;
}

public class A{
double height;
double weight;
}

public A getInfo(){
A a=new A();
a.height=2.5;
a.weight=3.7;
return a;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值