古人云,常言道,俗话说:“程序员如果没有对象,那就new一个”。
Java是面向对象编程,那么这个所谓的对象又是什么呢?拨开这层迷雾,理解什么是对象,我们就可以拥有属于自己真正的对象啦!
一、类
类,即模板,拥有共同属性的物体的集合。
//Person类,即:人 类
public class Person{
//人 所拥有的共同属性:name、age
String name;
int age;
}
二、对象
某一个类中的某一个具体个体。
// Person类中,有一个xiaoming
// xiaoming这个对象,属于Person类
Person xiaoming = new Person();
常言道:程序员如果没有对象,那就new一个
三、构造器
-
必须和类的名字相同
-
必须没有返回类型,也不能写void
作用:
- 使用new关键字,本质是在调用构造器
- 初始化值
public class Person{
//属性
String name;
int age;
//无参构造器
public Person(){
}
//有参构造器
public Person(String name){
this.name = name;
}
//有参构造器
public Person(String name, int age){
this.name = name;
this.age = age;
}
}
注意点:
- 定义有参构造之后,如果想使用无参构造,必须显示定义一个无参的构造
使用构造器:
//使用new关键字,本质是在调用构造器
Person xiaoming = new Person();//调用无参构造器,其name和age未赋值,为null
Person xiaohong = new Person("小红");//调用有参构造器,其name已赋值为“小红”,age未赋值 为null
Person xiaohua = new Person("小华",6);//调用有参构造器,其name已赋值为“小华”,age已赋值为 6
四、封装
- 提高程序的安全性,保护数据
- 隐藏代码的实现细节
- 统一接口
- 系统可维护增加
public class Student{
//使用private进行私有化封装
private String name;
private int id;
private char sex;
private int age;
//统一对外接口,为get和set方法
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
//外界只看到setAge方法,并不能看到代码实现的细节
public void setAge(int age) {
if(age>120 || age<0) {
this.age = 3;
}else {
this.age = age;
}
}
}
public class Application{
public static void main(String[] args){
Student s1 = new Student();
s1.setName("MoKi");
System.out.println(s1.getName());
s1.setName(150);
System.out.println(s1.getAge());
}
}
/*
MoKi
3
*/