Java基础七

1 成员变量和局部变量的区别

1.1 在类中的位置不同

  • 成员变量:类中方法外
  • 局部变量:方法内或方法声明上。

1.2 在内存中位置不同

  • 成员变量:堆内存。
  • 局部变量:栈内存。

1.3 生命周期不同

  • 成员变量:随着对象的存在而存在,随着对象的消失而消失。
  • 局部变量:随着方法的调用而存在,随着方法的调用完毕而消失。

1.4 初始化值不同

  • 成员变量:有默认的初始化值。
  • 局部变量:没有默认的初始化值,必须先定义,赋值,才能使用。

2 匿名对象

2.1 匿名对象概述

  • 匿名对象:就是没有名字的对象。

2.2 匿名对象的使用情况

  • 对象对象方法仅仅一次的情况。
  • 作为实际参数传递。

2.3 匿名对象的应用

  • 示例:
package com.xuweiwei;

public class Student {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
package com.xuweiwei;

public class StudentDemo {
    public static void main(String[] args) {
        Student s = new Student();
        s.setAge(26);
        s.setName("许威威");
        String result = s.toString();
        System.out.println(result);
    }
}
  • 示例:
package com.xuweiwei;

public class StudentDemo {
    public void method(Student s){
        System.out.println("result:"+s.toString());
    }
}
package com.xuweiwei;

public class StudentTest {
    public static void main(String[] args) {
        new StudentDemo().method(new Student());

    }
}

3 封装

3.1 封装的概述

  • 是指隐藏对象的属性和实现细节,仅仅对外提供公共访问方式。

3.2 封装的好处

  • 隐藏实现细节,提供公共的访问方式。
  • 提高了代码的复用性。
  • 提高安全性。

3.3 封装的原则

  • 将不需要对外提供的内容都隐藏起来。
  • 把属性隐藏,提供公共方法对其访问。

3.4 封装的应用

  • 示例:
package com.xuweiwei;

public class Student {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        if (age < 0 || age >= 150) {
            throw new RuntimeException("年龄输入不合法");
        }else{
            this.age = age;
        }
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
package com.xuweiwei;

public class StudentTest {
    public static void main(String[] args) {
        Student student = new Student();
        student.setName("许威威");
        student.setAge(-20);
        System.out.println(student);

    }
}

猜你喜欢

转载自www.cnblogs.com/xuweiweiwoaini/p/9196953.html