初识面向对象
类和对象的概念
- 类:是模子,确定对象将会拥有的特征(属性)和行为(方法)
- 对象:类的实例表现
- 属性:对象具有的各种静态特征,即“对象有什么”
- 方法:对象具有的各种动态行为,即“对象能做什么”
创建类和对象
定义类
#如果没有初始化属性值,那么会自动设置默认值

cat.java
定义类的属性和方法
package com.demo;/*** 宠物猫类** @author 57681**/public class Cat {// 属性String name;int age;double weight;String species;// 方法public void run() {System.out.println("I can run");}public void eat() {System.out.println("I can eat");}}
CatTest.java
实例化类的对象
package com.demo;public class CatTest {public static void main(String[] args) {// 对象实例化Cat kitty = new Cat();kitty.eat(); // I can eatkitty.run(); // I can runSystem.out.println(kitty.name); // nullSystem.out.println(kitty.age); // 0System.out.println(kitty.weight); // 0.0System.out.println(kitty.species); //null}}
实例化对象说明
实例化对象的过程可以分为两部分
- 声明对象 Cat kitty
在栈空间中开辟一个区域,取名叫kitty,但是此时还不能操作对象,因为里面是空的
- 实例化对象 new Cat()
在堆空间中开辟一个区域,同时初始化对象
实例化对象的完整操作:Cat kitty = new Cat();
kitty 中存放的是实例化之后对象的地址
构造方法
构造方法的特点
- 构造方法与类同名且没有返回值
- 访问修饰符可以省略
- 只能在对象实例化的时候调用
- 当没有指定构造方法时,系统会自动添加无参的构造方法
- 当有指定构造方法,无论有参,无参的构造方法,都不会自动添加无参的构造方法
- 一个类中可以有多个构造方法

构造方法的实例
Cat.java
package com.demo;/*** 宠物猫类** @author 57681**/public class Cat {// 属性String name;int age;double weight;String species;// 无参构造方法Cat() {System.out.println("我是无参构造方法");}// 有参构造方法Cat(String name, int age, double weight, String species) {this();this.name = name;this.age = age;this.weight = weight;this.species = species;}// 方法public void run() {System.out.println("I can run");}public void eat() {this.run(); // 调用成员方法,其实this可以省略,直接run()也是一样的效果System.out.println("I can eat");}}
CatTest.java
package com.demo;public class CatTest {public static void main(String[] args) {// 对象实例化Cat kitty = new Cat("kitty", 12, 24.5, "中华田园猫");kitty.eat(); // I can eatkitty.run(); // I can runSystem.out.println(kitty.name); // kittySystem.out.println(kitty.age); // 12System.out.println(kitty.weight); // 24.5System.out.println(kitty.species); // 中华田园猫}}
this关键字
- this指向的是当前的实例化对象
- this可以调用成员属性,解决成员属性和局部变量同名冲突
- this可以调用成员方法
- 在有参构造函数中,可以通过this()调用同一个类的无参构造方法,但是必须放在方法体内第一行
- 在无参构造函数中,可以通过this(参数)调用同一个类的有参构造方法,但是必须放在方法体内第一行
- 不能再静态方法中使用
