1. 对象
-
类是摸子,确定对象将会拥有的特征(属性)和行为(方法)
-
对象是类的实例表现
-
类是对象的类型
-
对象是特定类型的数据
-
属性:
- 对象具有的静态特征
- 系统会默认给其初始化赋值,直接调用不报错,比如
int
变量会赋0,String
给null
-
方法:
- 对象具有的动态行为
- 方法中定义的值不会初始化赋值,直接调用会报错
-
单一职责原则:一个类只有一个功能,只干一件事
-
举个例子
-
cat.java
package com.animal;
/**
* cat
* @author author
*
*/
public class Cat {
//属性:昵称、年龄、体重、品种
String name; //init: null
int month; //init: 0
double weight; //init: 0.0
String species;
//方法:跑动、吃东西
public void run() {
System.out.println("run");
}
public void run(String name) {
System.out.println(name+" run");
}
public void eat() {
System.out.println("eat");
}
}
catTest.java
,包含两种声明方式,需要注意相同的范围内,不能出现同名变量,下面那个例子中就是不能有两个one
package com.animal;
public class CatTest {
public static void main(String[] args) {
//对象实例化
Cat one = new Cat(); //第一种声明方式
new Cat().rum();//第二种声明方式:匿名声明
//测试
one.name = "cat";
one.month = 2;
one.weight = 1000;
one.eat();
one.run(one.name);
System.out.println("nickname: "+one.name);
System.out.println("age: "+one.month);
System.out.println("weight: "+one.weight);
System.out.println("species:"+one.species);
}
}
2. new关键字
- 作用:开辟新的堆空间
- 在上面的例子中,
Cat one = new Cat()
完成了两个动作,把对空间中开辟出的new Cat()
地址存到了栈空间的one
中- 声明对象:
Cat one
:在内存的栈空间中开辟了一个区域,取名one
,但这个时候还不是有效的对象,这个时候one
还是空的,如果要这个时候进行具体的操作是不被允许的 - 实例化对象:
new Cat()
:只有实例化之后才能调用具体操作,在堆空间内开了一个空间,完成了对象的相关信息的初始化操作。
- 声明对象:
- 栈是内存中的一个区域,保存局部变量
- 堆是内存中的另一个区域,保存动态数据
- 如果把代码修改一下,把
two=one
,那么对two
的任意改变都会直接作用在one
的身上,因为只是把one
的地址给了two
,是浅拷贝,下图可以解释其原理
package com.animal;
public class CatTest {
public static void main(String[] args) {
Cat one = new Cat();
Cat two = one;
}
}
3. 声明方式
- 基本用法:
Cat one = new Cat();
- 匿名声明:
new Cat().rum();
- 同时声明:
Cat one, two; one=new Cat(); two=new Cat();
或Cat three=new Cat(), four=new Cat();
- 注意不能在同一个命名空间里面有两个相同的变量名。也就是不能有两个
one
4. 构造方法
- 构造方法也称为:构造函数、构造器
- 要求:
- 在类外被调用的时候必须配备关键字,不能被单独调用
- 构造方法必须与类名相同,且没有返回值
- 只能在对象实例化的时候调用
- 特点:
- 当没有指定构造方法时,系统会自动添加无参的构造方法
- 当有指定构造方法,无论有参或无参,都不会自动添加无参的构造方法
- 一个类中可以有多个构造方法
- 用法:
public 构造方法名(){ //必须与类名相同,小括号里可以有参数,也可以没有
//初始化
}
- 还是之前小猫的例子,我们一旦定义了一个有参的构造函数,还想要一个无参的构造函数,我们需要在重载一个无参的函数
package com.animal;
/**
* cat
* @author author
*
*/
public class Cat {
//属性:昵称、年龄、体重、品种
String name; //init: null
int month; //init: 0
double weight; //init: 0.0
String species;
public Cat() { //需要构造两个,一个无参
}
public Cat(String name) { //一个有参
System.out.println(name);
}
//方法:跑动、吃东西
public void run() {
System.out.println("run");
}
public void run(String name) {
System.out.println(name+" run");
}
public void eat() {
System.out.println("eat");
}
}
5. this关键字
- 类似于
python
中的self
,但是不用在参数中写出来 - 代表这当前对象,可以
this.变量名
和this.函数名
,但调用函数名时可以省略this
- 在构造函数中用
this()
可以相互调用别的构造函数 - 我们可以写一个如下的构造函数
public Cat(String name, int month, double weight, String species) {
this.name = name;
this.month=month;
this.weight=weight;
this.species=species;
this.eat()
}