一,面向对象与面向过程的对比
面对过程:
当事件比较简单的时候,利用面向过程,注重的是事件的具体的步骤/过程,注重的是过程中的具体的行为,以函数为最小单位,考虑怎么做。 -----------在面向过程你是执行者
面对过程:
注重找“参与者”,将功能封装进对象,强调具备了功能的对象,以类/对象为最小单位,考虑谁来做。 ------------在面向对象你是指挥者
注: 二者相辅相成,并不是对立的。解决复杂问题,通过面向对象方式便于我们从宏观上把握事物之间复杂的关系、方便我们分析整个系统;具体到微观操作,仍然使用面向过程方式来处理。
面向对象的三阶段:
【1】面向对象分析OOA
-- Object Oriented Analysis
对象:张三,王五,朱六,你,我,
抽取出一个类---->人类
类里面有什么:
动词-->动态特性-->方法
名词-->静态特性-->属性
【2】面向对象设计OOD
-- Object Oriented Design
先有类,再有对象:
类:人类: Person
对象:zhangsan ,lisi,zhuliu
【3】面向对象编程OOP
--- Object Oriented Programming
详写类,方法,属性的代码细节
补:面对面向对象项目时处理思路:
a.将所有参与者向上提取,成为一个类。例如student
b.确定参与者有应该具备的行为---就是类中的方法
c.确定参与者应该具备的属性信息--就是类中的属性。
二,局部变量和成员变量区别:
声明位置不同:
局部变量在方法内。成员变量(属性)在方法外
默认值不同:
局部变量没有默认值;要先赋值再使用
成员变量有默认值:
String null
int 0
double 0.0
作用区域不同:
局部变量: 从声明变量开始,到包裹的大括号结束。
成员变量: 本类和其它类都可用。(成员变量也称全局变量)
本类调用:直接拿名用。 其它类使用:对象名.变量名 来调用
存在周期不同:
局部变量:从声明开始,到当前所在方法执行完,变量消失。
成员变量:从当前对象创建到对象被垃圾回收机制销毁。
所在内存中存储位置不同:
局部变量:在栈中,不稳定即用即清
成员变量:在堆里。垃圾回收机制处理。
注:当局部变量和成员变量同名时,使用this关键字进行区分。
三,this关键字:
(1)this可以修饰属性:
当属性名字和形参发生重名的时候,或者 属性名字 和局部变量重名的时候,都会发生就近原则,所以如果我要是直接使用变量名字的话就指的是离的近的那个形参或者局部变量,这时候如果我想要表示属性的话,在前面要加上:this.修饰
如果不发生重名问题的话,实际上你要是访问属性也可以省略this.
例:
public class Person {
//属性
int age;
String name;
double height;
//空构造器
public Person(){
}
//有参构造器
public Person(int age,String name,double height){
this.age = age;
this.name = name;
this.height = height;
}
//方法:
public void eat(){
int age = 10;
System.out.println(age);//就近原则,age指的是离它近的age-->局部变量的age
System.out.println(this.age);//这里指代的就是属性的age
System.out.println("我喜欢吃饭");
}
(2)this修饰方法:
在同一个类中,方法可以互相调用,this.可以省略不写。
例:
public class Person {
//属性
int age;
String name;
double height;
//空构造器
public Person(){
}
//有参构造器
public Person(int age,String name,double height){
this.age = age;
this.name = name;
this.height = height;
}
//方法:
/*public void eat(){
int age = 10;
System.out.println(age);//就近原则,age指的是离它近的age-->局部变量的age
System.out.println(this.age);//这里指代的就是属性的age
System.out.println("我喜欢吃饭");
}*/
public void play(){
/*this.*/eat();
System.out.println("上网");
System.out.println("洗澡");
}
public void eat(){
System.out.println(/*this.*/age);
System.out.println("吃饭");
}
}
(3)this可以修饰构造器:
即修饰构造方法。
同一个类中的构造器可以相互用this调用,注意:this修饰构造器必须放在第一行
例:
public class Person {
//属性
int age;
String name;
double height;
//空构造器
public Person(){
}
//有参构造器
public Person(int age,String name,double height){
this(age,name);
this.height = height;
}
public Person(int age,String name){
this(age);
this.name = name;
}
public Person(int age){
this.age = age;
}
//方法:
/*public void eat(){
int age = 10;
System.out.println(age);//就近原则,age指的是离它近的age-->局部变量的age
System.out.println(this.age);//这里指代的就是属性的age
System.out.println("我喜欢吃饭");
}*/
public void play(){
/*this.*/eat();
System.out.println("上网");
System.out.println("洗澡");
}
public void eat(){
System.out.println(/*this.*/age);
System.out.println("吃饭");
}
}