第十二章 无参和有参
无参方法public返回值 方法名(){//方法体
}
注意:
如果没有返回值,那么返回值类型是void.
如果有返回值,那么必须用return 返回值,并且该值的数据类型必须是定义方法
时的数据类型.
return的作用:
a.返回值
b.结束方法.(与break类似)2.写方法时注意
第一点:定义void为返回值类型时,不能使用return+返回值.
第二点:方法不能返回多个值.
第三点:方法不能嵌套.
第四点:不能在方法外部直接写程序逻辑代码.
有参方法1.方法的定义public返回值类型 方法名(参数类型1,参数名1,参数类型2,参数名2,.....参数类型n){//方法体
}2.有参数的调用
a.如果同一个类中,方法可以直接调用.
b.如果不同的类,方法必须通过对象调用,
对象名.方法名(实参,实参2...)
注意:1)实参的数据类型,参数的个数,参数的顺序要跟形象保持一致.2)调用有返回值的方法,一般要接受返回值,并作出相应的处理.public classExcelle {privateString type;privateString id;publicExcelle(){
}publicExcelle(String type,String id ){this.type =type;this.id =id;
}publicString getType(){returntype;
}publicString getId(){returnid;
}
}public classText {public static voidmain(String[] args){
Seller s= newSeller();
Excelle car= new Excelle("abc","1");
s.sell(car);
Regal cr= new Regal("bbb","2");
s.sell(cr);
Excelle ca= new Excelle("ccc","3");
s.sell(ca,5);
}
}public classStudent2 {
String name;intage;
String sex;
String subject;publicStudent2(){
}public Student2(String name,intage,String sex,String subject){this.name =name;this.age =age;this.sex =sex;this.subject =subject;
}publicString getName(){returnname;
}public intgetAge(){returnage;
}publicString getSex(){returnsex;
}publicString getSubject(){returnsubject;
}public voidbb(){
System.out.println("我是"+this.name+"年龄"+this.age+"性别"+this.sex+"专业"+this.subject);
}
}public classST2 {public static voidmain(String[] args){
Student2 s= new Student2("LL",14,"nan","aaa");
s.getAge();
s.getName();
s.getSex();
s.getSubject();
s.bb();
}
}