小峰视频十五:方法
一、基本的方法调用
public class Person {
//无参
void speak(){
System.out.println("我是袁隆盛!!");
}
//带参
void speak(String name){
System.out.println("我是"+name);
}
//多个参数
void speak(String name,int age){
System.out.println("我是"+name+",我今年"+age+"岁! ");
}
//不固定参数
void speak(String name,int age,String ...hobbies){
System.out.println("我是"+name+",我今年"+age+"岁! ");
for (String hobby : hobbies) {
System.out.print(hobby+" ");
}
}
//有返回值
int speak01(String name,int age,String ...hobbies){
System.out.println("我是"+name+",我今年"+age+"岁! ");
for (String hobby : hobbies) {
System.out.print(hobby+" ");
}
return hobbies.length;
}
public static void main(String[] args) {
Person p = new Person();
p.speak();
p.speak("袁隆盛");
p.speak("袁隆盛", 25);
p.speak("袁隆盛", 25, "乒乓球","唱歌","编程");
int n = p.speak01("袁隆盛", 25, "乒乓球","唱歌","编程");
System.out.println("我有"+n+"个爱好");
}
}
二、参数的传递
public class Person02 {
void speak(int age){
System.out.println("我今年"+age+"!");
age = 24;
System.out.println(age);//输出24
}
public static void main(String[] args) {
Person02 p2 = new Person02();
int age = 23;
p2.speak(age);
System.out.println(age);//输出23,方法里面的变动不影响外侧的结果
}
}
class Sanwei{
int xiongwei;
int tunwei;
int jianwei;
}
public class Person03 {
void speak(Sanwei sanwei){
sanwei.xiongwei = 20;
sanwei.tunwei = 20;
sanwei.jianwei = 20;
System.out.println("我的三围是:"+sanwei.xiongwei+" "+sanwei.tunwei+" "+sanwei.jianwei);//输出20
}
public static void main(String[] args) {
Sanwei sanwei = new Sanwei();
sanwei.xiongwei = 30;
sanwei.tunwei = 30;
sanwei.jianwei = 30;
Person03 p = new Person03();
System.out.println("我的三围是:"+sanwei.xiongwei+" "+sanwei.tunwei+" "+sanwei.jianwei);//输出30
p.speak(sanwei);
}
}
public class Person {//无参void speak(){System.out.println("我是袁隆盛!!");}//带参void speak(String name){System.out.println("我是"+name);}//多个参数void speak(String name,int age){System.out.println("我是"+name+",我今年"+age+"岁!");}//不固定参数void speak(String name,int age,String ...hobbies){System.out.println("我是"+name+",我今年"+age+"岁!");for (String hobby : hobbies) {System.out.print(hobby+" ");}}//有返回值int speak01(String name,int age,String ...hobbies){System.out.println("我是"+name+",我今年"+age+"岁!");for (String hobby : hobbies) {System.out.print(hobby+" ");}return hobbies.length;}public static void main(String[] args) {Person p = new Person();p.speak();p.speak("袁隆盛");p.speak("袁隆盛", 25);p.speak("袁隆盛", 25, "乒乓球","唱歌","编程");int n = p.speak01("袁隆盛", 25, "乒乓球","唱歌","编程");System.out.println("我有"+n+"个爱好");}}

浙公网安备 33010602011771号