方法
动态 功能
写在类中
非静态:对象.方法()
静态 :类名.static方法()
同一类中: class A{ a() ; b() } ;
public void a()
{
b();
}
public class MethodReturn {
public void a(){
System.out.println("zs");
}
public void b(){
a();
}
public static void main(String[] args) {
MethodReturn method = new MethodReturn();
method.a();
}
}
返回值
无范围值
有返回值
public 返回值类型 方法名()
{
return 类型对应的数据
}
public int a()
{
return 1;
}
public class MethodReturn {
public void a(){
System.out.println("zs");
}
public String a1(){
String name = "zs";
//System.out.println(name);
return name;
}
public void b(){
//a();
String name = a1(); //2.调a1,返回a1中的name给b中的name
System.out.println("b:"+name);
}
public static void main(String[] args) {
MethodReturn method = new MethodReturn();
method.b(); //1.调b
}
}
在调用有返回值的方法时,需要接收 String xx = a1( ) ;
面向对象编程
例
从键盘接收:计算三门课的平均成绩、总成绩
import java.util.Scanner;
public class OOPScore {
//属性(静态行为)、全局变量
int javaScore ;
int cScore ;
int sqlScore ;
public void inputScore(){
Scanner input = new Scanner(System.in);
System.out.println("请输入JAVA成绩");
javaScore = input.nextInt();
System.out.println("请输入C成绩");
cScore = input.nextInt();
System.out.println("请输入SQL成绩");
sqlScore = input.nextInt();
}
//计算平均分并返回
public double calcAvg(){
double av =(javaScore+cScore+sqlScore)/3.0;
return av;
}
//计算总分返回
public int calcSum(){
int sum = javaScore+cScore+sqlScore;
return sum;
}
public static void main(String[] args) {
OOPScore score = new OOPScore();
score.inputScore();
double avg = score.calcAvg();
int sum = score.calcSum();
System.out.println(avg +"---" +sum);
}
}
参数
个性化,谁在睡觉
sleep1(String name)
public class People {
public void sleep(){ //无参:()里没东西
System.out.println("睡觉...");
}
public void sleep1(String name){ //有参 String name 个性化 形参:name
System.out.println(name+"睡觉...");
}
public static void main(String[] args) {
People zs = new People();
zs.sleep1("张三"); //实参:张三
People ls = new People();
ls.sleep1("李四");
}
}
输出:
张三睡觉...
李四睡觉...
更加个性化 :谁在哪里睡觉
sleep1(String name,String place)
public class People {
public void sleep(){
System.out.println("睡觉...");
}
public void sleep1(String name,String place){
System.out.println(name+"在"+place+"睡觉...");
}
public static void main(String[] args) {
People zs = new People();
zs.sleep1("张三","家里");
People ls = new People();
ls.sleep1("李四","宾馆");
}
}
输出:
张三在家里睡觉...
李四在宾馆睡觉...
参数越多越个性化,但太多就很麻烦,可用数组简化
lic class People {
public void sleep(){
System.out.println("睡觉...");
}
public void sleep1(String name,String place,String time){
System.out.println(name+"在"+place+"睡觉,时间"+time);
}
//数组infos = {name,place,time}
public void sleep2(String[] infos){
System.out.println(infos[0]+"在"+infos[1]+"睡觉,时间"+infos[2]);
}
public static void main(String[] args) {
People zs = new People();
//数组infos = {name,place,time}
String[] zsinfos = {"张三","家里","20:22"};
zs.sleep2(zsinfos);
People ls = new People();
String[] lsinfos = {"李四","宾馆","21:22"};
ls.sleep2(lsinfos);
}
输出:
张三在家里睡觉,时间20:22
李四在宾馆睡觉,时间21:22