对象的行为

来源:互联网 发布:手机五线谱制作软件 编辑:程序博客网 时间:2024/05/29 07:36

状态影响行为,行为影响状态.
我们都知道对象有行为和状态两种属性.
类是一个抽象的蓝图,所描述的就是对象知道什么可以执行什么.

方法的参数 我们可以传值给方法

public class dog {    String dog;    int age;    public static void main(String[] args) {        dog d = new dog();// 创建对象        d.song(3);// 调用狗叫的方法并且进行传值    }    void song(int a) {        System.out.println("这个狗叫了" + a + "声");    }}

由于不同的程序设计你可能会用到形参和实参那么我们要如何区分它们呢?
方法运用形参,调用的一方传入实参

方法生成void类型 代码不需要返回任何东西

如果方法被设置成有返回值,就必须返回声明的类型值

public class dog {    String dog;    int age;    public static void main(String[] args) {        dog d = new dog();// 创建对象        int song = d.song(3);// 调用狗叫的方法并且进行传值        System.out.println(song);    }    int song(int a) {        System.out.println("这个狗叫了" + a + "声");        return a;    }}

你还可以向方法里面传入一个以上的参数

public class dog {    String dog;    int age;    public static void main(String[] args) {        dog d = new dog();// 创建对象        int song = d.song(12, 2);        System.out.println(song);    }    int song(int a,int b) {        return a*b;    }}

并且还可以传入变量呢

public class dog {    String dog;    int age;    public static void main(String[] args) {        dog d = new dog();// 创建对象        int x = 7;        int y = 2;        int song = d.song(x,y);        System.out.println(song);    }    int song(int a,int b) {        return a*b;    }}

java是通过值传递的
这里写图片描述

其实就是拷贝的值
需要注意的是:方法只能声明单一的返回值