JavaSE 第十讲 面向对象之封装.续 9.28

1、对象又叫做实例(instance),生成一个对象的过程又叫做实例化。

2、如何定义属性?

public class Person
{
      修饰符 类型 属性名称;
}

如何使用属性?
首先需要生成类的实例(对象),然后用实例+“.”的方法使用属性。如
Person person = new Person();
person.age;

public class Person
    {
         int age ;
     boolean flag;

     public static void main(String[] args)
     {
             Person person = new Person();
         System.out.println(person.age);
         System.out.println(person.flag);
     }
    }

3、引用

public class People
{
    int age = 20;

public void change(People people)
{
    people.age = 30;
}

public static void main(String[] args)
{
         People people = new People();

     int age = people.age;

     System.out.println(age);

     people.change(people);

     int age2 = people.age;

         System.out.println(age2);//结果:20 30

}
}
微信截图_20161125085517.png
public class People
    {
        int age = 20;

    public void change(People people)
    {
            people = new People(); 
        
        people.age = 30;
    }

    public static void main(String[] args)
    {
             People people = new People();

         int age = people.age;

         System.out.println(age);

         people.change(people);

         int age2 = people.age;

             System.out.println(age2);//结果:20 20

    }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容