第十二章 无参和有参
无参方法
public 返回值 方法名(){
//方法体
}
注意:
如果没有返回值,那么返回值类型是void.
如果有返回值,那么必须用return 返回值,并且该值的数据类型必须是定义方法
时的数据类型.
return的作用:
a.返回值
b.结束方法.(与break类似)
2.写方法时注意
第一点:定义void为返回值类型时,不能使用return+返回值.
第二点:方法不能返回多个值.
第三点:方法不能嵌套.
第四点:不能在方法外部直接写程序逻辑代码.
有参方法
1.方法的定义
public 返回值类型 方法名(参数类型1,参数名1,参数类型2,参数名2,.....参数类型n){
//方法体
}
2.有参数的调用
a.如果同一个类中,方法可以直接调用.
b.如果不同的类,方法必须通过对象调用,
对象名.方法名(实参,实参2...)
注意:
1)实参的数据类型,参数的个数,参数的顺序要跟形象保持一致.
2)调用有返回值的方法,一般要接受返回值,并作出相应的处理.
public class Excelle {
private String type;
private String id;
public Excelle(){
}
public Excelle(String type,String id ){
this.type = type;
this.id = id;
}
public String getType(){
return type;
}
public String getId(){
return id;
}
}
public class Text {
public static void main(String[] args){
Seller s = new Seller();
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 class Student2 {
String name;
int age;
String sex;
String subject;
public Student2(){
}
public Student2(String name,int age,String sex,String subject){
this.name = name;
this.age = age;
this.sex = sex;
this.subject = subject;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public String getSex(){
return sex;
}
public String getSubject(){
return subject;
}
public void bb(){
System.out.println("我是"+this.name+"年龄"+this.age+"性别"+this.sex+"专业"+this.subject);
}
}
public class ST2 {
public static void main(String[] args){
Student2 s = new Student2("LL",14,"nan","aaa");
s.getAge();
s.getName();
s.getSex();
s.getSubject();
s.bb();
}
}