封装概述:
是面向对象三大特征之一(封装,继承,多态)
是面向对象编程语言对客观世界的模拟,客观世界里的成员变量都是隐藏在对象内部的,外界无法直接操作的。
封装原则:
将类的某些信息隐藏在类内部,不允许外部程序直接访问,而是通过该类提供的方法来实现对隐藏信息的操作和访问
成员变量:private,提供对应的getXxx()/setXxx()方法
封装的好处:
通过方法来控制成员变量的操作,提高了代码的安全性。
把代码用方法进行封装,提高了代码的复用性
构造方法的概述:
构造方法格式:
public class 类名{
修饰符 类名(参数){
}
}
范例:
public class Student(){
public Student(){
}
}
Student类:
package com.itheima01;
public class Student {
private String name;
private int age;
//构造方法
public Student(){
}
public Student(String name){
this.name=name;
}
public Student(int age){
this.age=age;
}
public Student(String name,int age){
this.name=name;
this.age=age;
}
public void show(){
System.out.println(name+","+age);
}
}
测试类:
package com.itheima01;
//测试类
public class StudentDemo {
public static void main(String[]args){
//创建对象
Student s1=new Student();
s1.show();
Student s2=new Student("林青霞");
s2.show();
Student s3=new Student(30);
s3.show();
Student s4=new Student("林青霞",30);
s4.show();
}
}