定义
面向对象和面向过程的思想对比
- 面向过程编程 Procedure Oriented Programming
以过程为中心,实现功能的每一步,都是自己实现的 - 面向对象Object Oriented Programming
以对象为中心,指挥对象实现具体功能List item
对象:客观存在的事务
- 客观存在的任何一种事务都可以看做程序中的对象
- 使用面向对象思想可以将复杂问题简单化
- 由执行者变成指挥者
类和对象
类是对象的描述,
对象是类的实体,
类的定义
成员变量和局部变量
成员变量:类中方法外
局部变量:方法中
封装
-
private关键字
被private修饰的关键字只能在类中使用 -
this 关键字
将变量变成成员变量
java为就近原则,
private int age;
public void setAge(int age){//age为局部变量
this.age=age;
}
封装
面向对象三大特征:封装,继承,多态
隐藏实现细节,仅暴露公共的访问方式
私有仅仅是封装的一种体现
构造方法
构建 ,创造对象的时候,所调用的方法
方法名和类名要完全一致
构造方法的作用
给对象的数据(属性)进行初始化
public class Student {
private String name;
private int age;
public Student(String name,int age){
this.name=name;
this.age=age;
System.out.println("我是student类的构造方法");
}
public void show(){
System.out.println(name+"..."+age);
}
}
public class TestStudent {
public static void main(String[] args) {
// Student stu=new Student();//stu是对象
Student stu2=new Student("张三",23);
Student stu3=new Student("张si",25);
}
}
注意事项
//如果一个类中没有编写任何构造方法,系统会提供一个默认的无参数构造方法
//如果手动编写了构造方法,系统就不会在提供默认无参数构造方法
建议:无参数的构造方法和有参数的构造方法都一并写出
public Student(){}//系统默认无参数构造方法
public Student(String name,int age){
this.name=name;
this.age=age;
}
标准类的代码编写和使用
代办
06,07单个对象内存图
this关键字和内存原理