类的方法:提供某种功能的实现:
实例:public void eat (){ }
public String getName(){ }
public void setName(String n){ }
格式:权限修饰符 返回值类型(void:无返回值/具体的返回值) 方法名(形参){ }
注意:返回值类型 void 表名此方法不需要你返回值
有返回值的方法:在方法的最后一定有 return+返回值类型对象的变量
记忆:void 和 return不能让同时存在;
※ 可以在方法内调用本类的其他方法,但是不可以在方法内定义新的方法
练习1:
public class TestPerson {
public static void main(String[] args) {
Person p = new Person();
p.study();
p.showAge();
p.addAge(2);
p.showAge();
Person p1 = new Person();
p1.showAge();// 0
}
}
class Person {
String name;
int age;
int sex;
public void study() {
System.out.println("学习");
}
public void showAge() {
System.out.println(age);// 打印调用showAge()方法的对象的age属性
}
public int addAge(int i) {// 给调用此方法的对象age属性增加i岁,并返回新的age
age += i;
return age;
}
}
练习2.
用面向对象的编程,设计Circle计算圆的面积、
public class TestCircle {
public static void main(String[] args) {
Circle c = new Circle();
c.redius = 2.4;
c.findArea();
}
}
class Circle {
double redius = 1.0;// 半径
// 提供方法,用于获取圆的面积
public void findArea() {
System.out.println(3.14 * redius * redius);//此处的redius为调用findArea()方法的对象的属性redius 2.3
}
}
All that work will definitely pay off