六、面向对象

1. 初识面向对象

1.1 比较面向过程和面向对象

  • 面向过程思想:步骤清晰简单,第一部做什么,第二步做什么......(微观)

  • 面向对象思想:分类的思维模式,属性+方法=类。(宏观)

1.2 什么是面向对象

  • 面向对象编程 Object-Oriented Programming (OOP)
  • 面向对象编程的本质:以类的方式组织代码,以对象的形式封装数据
  • 抽象
  • 三大特性:封装、继承、多态
  • 从认识论角度考虑是先有对象后有类。对象,是具体的事物。类,是抽象的,是对对象的抽象。
  • 从代码运行角度考虑是先有类后有对象。类是对象的模板。

2. 方法回顾和加深

2.1 方法的定义

  • 修饰符
  • 返回类型
  • break和return的区别
  • 方法名
  • 参数列表
  • 异常抛出
package com.snmwyl.oop;

import java.io.IOException;

//Demo1 类
public class Demo1 {
    //main 方法
    public static void main(String[] args){

    }

    /*
    修饰符 返回值类型 方法名(参数列表){
        方法体
        return 返回值;
    }
     */
    public String sayHello(){
        return "Hello World";   //return结束方法。break跳出switch,结束循环。
    }
    public int max(int a, int b){   //参数列表(参数类型 参数名)
        return a > b ? a : b;   //三元运算符
    }
    //数组下标越界:ArrayIndexOutOfBoundsException
    public void readFile(String file) throws IOException {

    }
}

2.2 方法的调用

  • 静态方法
  • 非静态方法
  • 形参和实参
  • 值传递和引用传递
  • this关键字
package com.snmwyl.oop;

//学生类
public class Student {
    //静态方法 static,和类一起加载到
    public static void say1(){
        System.out.println("你好。");
    }

    //非静态方法,类实例化后才存在
    public void say2(){
        System.out.println("Helo.");
    }
}
package com.snmwyl.oop;

public class Demo2 {
    public static void main(String[] args) {
        //类名. 方法名
        Student.say1();   //你好。

        //实例化这个类 new
        new Student().say2();   //Helo.

        //对象类型 对象名 = 对象值
        Student student = new Student();
        student.say2();   //Helo.
    }
}
package com.snmwyl.oop;

public class Demo3 {
    public static void main(String[] args) {
        //值传递
        int a = 1;
        System.out.println(a);   //1
        Demo3.changeNum(a);
        System.out.println(a);   //1

        //引用传递
        Person person = new Person();
        System.out.println(person.name);   //null
        Demo3.changeName(person);
        System.out.println(person.name);   //kitty
    }

    public static void changeNum(int a) {
        a = 2;
    }

    public static void changeName(Person person) {
        person.name = "kitty";
    }
}

class Person {
    String name;
}

3. 对象的创建分析

3.1 类与对象的关系

  • 类是一种抽象的数据类型,它是对某一类事物整体描述/定义,但是并不能代表某一个具体的事物
  • 对象是对抽象概念的具体实例

3.2 创建与初始化对象

  • 使用new关键字创建对象的时候,除了分配内存空间之外,还会给创建好的对象进行默认的初始化以及对类中构造器的调用
  • 类中的构造器也称为构造方法,是在进行创建对象的时候必须要调用的。并且构造器有以下两个特点:

​ 。必须和类的名字相同

​ 。必须没有返回类型,也不能写

package com.snmwyl.oop.Demo4;

//学生类
public class Student {
    //属性:字段
    String name;  //null
    int age;      //0

    //方法
    public void study(){
        System.out.println(this.name+"在学习。");
    }
}
package com.snmwyl.oop.Demo4;

//一个项目应该只存一个main方法
public class Application {
    public static void main(String[] args) {
        //类:抽象的,实例化
        //类实例化后会返回一个自己的对象
        //student对象就是一个Student类的具体实例

        Student zhang = new Student();
        Student yang = new Student();

        zhang.name = "小明";
        zhang.age = 12;

        System.out.println(zhang.name);  //小明
        System.out.println(zhang.age);   //12
        System.out.println(yang.name);   //null
        System.out.println(yang.age);    //0
    }
}
  • 以类的方式组织代码,以对象的形式封装数据

3.3 构造器详解

package com.snmwyl.oop.Demo4;

public class Person {
    /*
    默认存在一个方法
    Person person(){
    }
     */

    //显式的定义构造器
    String name;

    //实例化初始值
    //使用new关键字,本质是在调用构造器
    //用来初始化值
    public Person(){
        this.name = "zhang";
    }

    //有参构造
    //一旦定义了有参构造,无参就必须显式定义
    public Person(String name){
        this.name = name;
    }
}
package com.snmwyl.oop.Demo4;

//一个项目应该只存一个main方法
public class Application {
    public static void main(String[] args) {
        //new 实例化了一个对象
        Person person = new Person();
        System.out.println(person.name);  //zhang
    }
}

3.4 创建对象内存分析

package com.snmwyl.oop.Demo4;

public class Pet {
    public String name;
    public int age;

    //无参构造

    public void speak(){
        System.out.println("I'm a pet...");
    }
}
package com.snmwyl.oop.Demo4;

//一个项目应该只存一个main方法
public class Application {
    public static void main(String[] args) {
        Pet dog = new Pet();
        dog.name = "Dog";
        dog.age = 3;
        dog.speak();

        Pet cat = new Pet();
    }
}

image-20251220213926379

3.5 简单小结类与对象

  1. 类与对象

    类是一个模板,抽象。对象是一个具体的实例。

  2. 方法

​ 定义。调用。

  1. 对应的引用

​ 引用类型。基本类型(8)。

​ 对象是通过引用来操作的:栈--->堆

  1. 属性/字段/Field/成员变量

​ 默认初始化:

​ 数字:0 0.0

​ char:u0000

​ boolean:false

​ 引用:null

​ 修饰符 属性类型 属性名 = 属性值;

  1. 对象的创建和使用

​ -- 必须使用new关键字创建对象,构造器。

​ -- 对象的属性

​ -- 对象的方法

  1. 类:

​ 静态的属性/属性

​ 动态的行为/方法

4. 面向对象三大特性

4.1 封装

  • 高内聚:类的内部数据操作细节自己完成,不允许外部干涉。
  • 低耦合:仅暴露少量的方法给外部使用。
  • 属性私有:get/set
package com.snmwyl.oop.Demo5;

public class Student {
    /*
    封装作用:
    1.提高程序的安全性,保护数据
    2.隐藏代码的实现细节
    3.统一接口
    4.系统可维护性增加
     */

    //属性私有
    private String name;   //姓名
    private int age;   //年龄

    //提供一些可以操作这个属性的public的方法
    public String getName(){
        return this.name;
    }

    public void setName(String name){
        this.name = name;
    }

    public int getAge(){
        return this.age;
    }

    public void setAge(int age){
        if(age>100 || age<0){
            System.out.println("Invalid Age");
            this.age = 1;
        }else{
            this.age = age;
        }
    }
}
package com.snmwyl.oop.Demo4;
import com.snmwyl.oop.Demo5.Student;
//一个项目应该只存一个main方法
public class Application {
    public static void main(String[] args) {
        Student s1 = new Student();
        String name = s1.getName();
        System.out.println(name);   //null
        s1.setName("kitty");
        System.out.println(s1.getName());   //kitty
        s1.setAge(999);   //Invalid Age
        System.out.println(s1.getAge());   //1
        s1.setAge(20);
        System.out.println(s1.getAge());   //20
    }
}

4.2 继承

  • 继承的本质是对某一批类的抽象,从而实现对现实世界更好的建模。
  • extends的意思是“扩展”。子类是父类的扩展。
  • Java中类只有单继承,没有多继承。
  • 继承是类和类之间的一种关系。除此之外,类和类之间的关系还有依赖、组合、聚合等。
  • 继承关系的两个类,一个为子类(派生类),一个为父类(基类)。子类继承父类,使用关键字extends来表示。
  • 子类和父类之间,从意义上讲应该具有“is a”的关系。
  • object类
  • super
  • 方法重写
package com.snmwyl.oop.Demo6;

//Student is 人
//子类 派生类
//子类继承了父类,就会拥有父类的全部方法
public class Student extends Person {
    /*
    组合
    Person person;
     */
    //隐藏代码,调用父类的无参构造,必须在子类构造器的第一行。super和this不能同时调用构造方法。
    //super();
    public Student(){   //构造器
        System.out.println("Student无参执行了");
    }
    private String name = "Kitty";
    public void sayHello() {
        System.out.println("hello!");
    }
    /*
    比较this和super
    1.代表对象不同
        this:调用者本身这个对象
        super:代表父类对象的引用
    2.前提
        this:没有继承也可以使用
        super:只有在继承条件下才可以使用
    3.构造方法
        this():本类的构造
        super():父类的构造
     */
    public void test1(String name){
        System.out.println(name);
        System.out.println(this.name);
        System.out.println(super.name);
    }
    public void test2(){
        sayHello();
        this.sayHello();
        super.sayHello();
    }
}
package com.snmwyl.oop.Demo4;

import com.snmwyl.oop.Demo6.Student;
//一个项目应该只存一个main方法
public class Application {
    public static void main(String[] args) {
        Student student = new Student();   //Person无参执行了 Student无参执行了
        student.sayHello();   //Hello.
        System.out.println(student.getMoney());   //100000000
        student.test1("猫");   //猫 Kitty Kitten
        student.test2();   //hello! hello! Hello.
    }
}
package com.snmwyl.oop.Demo7;

//重写都是方法的重写,和属性无关
public class B {
    public static void test1(){
        System.out.println("B1");
    }
    public void test2(){
        System.out.println("B2");
    }
}
package com.snmwyl.oop.Demo7;

//继承
public class A extends B {
    public static void test1(){
        System.out.println("A1");
    }

    //Override 重写
    @Override   //注解,有功能的注释
    public void test2(){
        System.out.println("A2");
    }
    /*
    重写Override:需要有继承关系,子类重写父类的方法
        1.方法名必须相同
        2.参数列表必须相同
        3.方法体不同
        4.修饰符范围可以扩大但不能缩小:public>protected>default>private
        5.抛出的异常范围可以被缩小但不能扩大:Exception>calssNotFoundException
    为什么需要重写:
        父类的功能,子类不一定需要,或不一定满足
     */
}
package com.snmwyl.oop.Demo4;

import com.snmwyl.oop.Demo7.A;
import com.snmwyl.oop.Demo7.B;

//一个项目应该只存一个main方法
public class Application {
    public static void main(String[] args) {
        A a = new A();
        B b = new A();   //父类的引用指向了子类

        //静态方法的调用只和左边定义的数据类型有关
        A.test1();   //A1
        B.test1();   //B1

        //非静态方法,子类重写了父类的方法
        a.test2();   //A2
        b.test2();   //A2
    }
}

4.3 多态

  • 同一方法可以根据发送对象的不同而采用多种不同的行为方式
  • 一个对象的实际类型是确定的,但可以指向对象的引用的类型有很多
  • 多态存在的条件:

​ 。有继承关系

​ 。子类重写父类的方法

​ 。父类引用指向子类对象

  • 多态是方法的多态,属性没有多态性
  • instanceof
package com.snmwyl.oop.Demo8;

public class Person {
    public void run() {
        System.out.println("Person is running.");
    }
}
package com.snmwyl.oop.Demo8;

public class Student extends Person {
    @Override
    public void run() {
        System.out.println("Student is running.");
    }
    public void study() {
        System.out.println("Student is studying.");
    }
}
package com.snmwyl.oop.Demo4;
import com.snmwyl.oop.Demo8.Student;
import com.snmwyl.oop.Demo8.Person;

//一个项目应该只存一个main方法
public class Application {
    public static void main(String[] args) {

        //一个对象的实际类型是确定的
        //new Student();
        //new Person();

        //可以指向的引用类型不确定
        Student s1 = new Student();
        Person s2 = new Student();   //父类的引用指向子类
        Object s3 = new Student();

        s1.run();   //Student is running.
        //子类重写了父类的方法,执行子类的方法
        s2.run();   //Student is running.

        s1.study();   //Student is studying.
        ((Student) s2).study();   //Student is studying.
        //类型转换异常:ClassCastException

        /*
        1.对象能执行哪些方法,主要看对象左边的类型
        2.子类重写了父类的方法,执行子类的方法
        3.Student能调用的方法都是自己的或者继承父类的
        4.Person可以指向子类,但不能调用子类独有的方法
        5.多态存在条件:继承关系,方法需要重写,父类引用指向子类对象
        6.不能被重写的方法:
            - static方法,属于类,不属于实例
            - final,常量
            - private,私有
         */
    }
}
package com.snmwyl.oop.Demo4;
import com.snmwyl.oop.Demo8.Teacher;
import com.snmwyl.oop.Demo8.Student;
import com.snmwyl.oop.Demo8.Person;
//一个项目应该只存一个main方法
public class Application {
    public static void main(String[] args) {
    //Object>Person>Student
    //Object>Person>Teacher
    //Object>String
    Object object = new Student();
    System.out.println(object instanceof Student);   //true
    System.out.println(object instanceof Person);   //true
    System.out.println(object instanceof Object);   //true
    System.out.println(object instanceof Teacher);   //false
    System.out.println(object instanceof String);   //false
    System.out.println("====================");
    Person person = new Student();
    System.out.println(person instanceof Student);   //true
    System.out.println(person instanceof Person);   //true
    System.out.println(person instanceof Object);   //true
    System.out.println(person instanceof Teacher);   //false
    System.out.println(object instanceof String);   //false
    System.out.println("====================");
    Student student = new Student();
    System.out.println(person instanceof Student);   //true
    System.out.println(person instanceof Person);   //true
    System.out.println(person instanceof Object);   //true
    System.out.println(person instanceof Teacher);   //false
    System.out.println(object instanceof String);   //false
    }
}
package com.snmwyl.oop.Demo4;
import com.snmwyl.oop.Demo8.Person;
import com.snmwyl.oop.Demo8.Student;
//一个项目应该只存一个main方法
public class Application {
    public static void main(String[] args) {
        //类型之间的转换

        //子类转换为父类(低转高,自动转换),可能丢失自己的本来的一些方法
        Person student = new Student();

        //父类转化为子类(高转低,强制转换)
        ((Student)student).study();   //study
    }
}
package com.snmwyl.oop.Demo9;

public class Student {
    //静态的变量 多线程
    private static int age;
    //非静态的变量
    private double score;
    //静态的方法
    public static void play() {
        System.out.println("play");
    }
    //非静态的方法
    public void study() {
        System.out.println("study");
    }

    public static void main(String[] args) {
        Student s1 = new Student();
        System.out.println(Student.age);   //0
        //System.out.println(Student.score);编译报错
        //无法从静态上下文中引用非静态 变量 score
        System.out.println(s1.age);   //0
        System.out.println(s1.score);   //0.0

        //study();编译报错
        // 无法从静态上下文中引用非静态方法study()
        Student s2 = new Student();
        s2.study();   //study
        play();   //play
    }
}
package com.snmwyl.oop.Demo9;

public class Person {
    //2.匿名代码块
    //作用:赋初始值
    {
        System.out.println("匿名代码块");
    }

    //1.静态代码块
    //只执行一次
    static{
        System.out.println("静态代码块");
    }

    //3.构造方法
    public Person(){
        System.out.println("构造方法");
    }

    public static void main(String[] args) {
        Person person1 = new Person();
        /*
        静态代码块
        匿名代码块
        构造方法
         */
        System.out.println("==========");
        Person person2 = new Person();
        /*
        匿名代码块
        构造方法
         */
    }
}
package com.snmwyl.oop.Demo9;

//静态导入包
import static java.lang.Math.random;
import static java.lang.Math.PI;

public class Test {
    public static void main(String[] args) {
        System.out.println(random());
        System.out.println(PI );   //3.141592653589793
    }
}

5. 抽象类和接口

  • abstract修饰符可以用来修饰方法也可以修饰类。如果修饰方法,那么该方法就是抽象方法;如果修饰类,那么该类就是抽象类。
  • 抽象类中可以没有抽象方法,但是但是有抽象方法的类一定要声明为抽象类。
  • 抽象类,不能使用new关键字来创建对象,它是用来让子类继承的。
  • 抽象方法,只有方法的声明,没有方法的实现,它是用来让子类实现的。
  • 子类继承抽象类,那么就必须要实现抽象类没有实现的方法,否则该子类也要声明为抽象类。
package com.snmwyl.oop.Demo10;

public abstract class Action {
    //约束,有人帮我们实现
    //abstract,抽象方法,只有方法名字,没有方法的实现
    public abstract void act();
    public void sayHello() {
        System.out.println("Hello.");
    }
    //1.不能new这个抽象类,只能靠子类去实现它
    //2.抽象类中可以写普通的方法
    //3.抽象方法必须在抽象类中
    //4.抽象类有构造器,用于被子类调用,以完成抽象类中定义的状态初始化
    /*5.抽象类意义:
        - 代码复用与实现共享
        - 定义模板方法模式
        - 强制子类实现特定行为
        - 提供部分实现,减少重复代码
        - 控制子类的扩展方式
     */
}
package com.snmwyl.oop.Demo10;

//extends单继承,接口可以多继承
public class A extends Action{

    @Override
    public void act() {

    }
}
package com.snmwyl.oop.Demo4;

public interface UserService {
    //属性默认修饰符public static final
    int age = 20;   //常量

    //接口中的所有定义的方法都是抽象的,默认修饰符public abstract
    //接口都需要实现类
    void add(String name);
    void delete(String name);
    void update(String name);
    void query(String name);

    //接口不能被实例化,接口中没有构造方法
}
package com.snmwyl.oop.Demo4;

public interface TimeService {
    void timer();
}
package com.snmwyl.oop.Demo4;

//利用接口实现多继承
public class UserServiceImpl implements UserService,TimeService {

    @Override
    public void add(String name) {

    }

    @Override
    public void delete(String name) {

    }

    @Override
    public void update(String name) {

    }

    @Override
    public void query(String name) {

    }

    @Override
    public void timer() {

    }
}

6. 内部类及OOP实战

  1. 成员内部类
  2. 静态内部类
  3. 局部内部类
  4. 匿名内部类
package com.snmwyl.oop.Demo11;

//一个Java类中可以有多个class类,但是只能有一个public class类

//外部类
public class Outer {
    private int id = 10;

    public void out() {
        System.out.println("我是外部类的一个方法。");
    }

    //成员内部类
    public class Inner1 {
        public void in() {
            System.out.println("我是内部类的一个方法。");
        }

        //获得外部类的私有属性
        public void getID() {
            System.out.println(id);
        }
    }

    //静态内部类
    //不能直接访问非静态属性
    public static class Inner2 {
        public void in() {
            System.out.println("我是内部类的一个方法。");
        }
    }

    //局部内部类
    public void method() {
        class Inner3 {
            public void in() {
            }
        }
    }

    //匿名内部类
    //不用将实例保存到变量中
    public static void main(String[] args) {
        new Apple().eat();   //eating apple
    }

    //匿名内部类
    UserService userService = new UserService() {
        @Override
        public void hello() {

        }
    };
}

class Apple{
    public void eat(){
        System.out.println("eating apple");
    }
}

interface UserService{
    void hello();
}
package com.snmwyl.oop.Demo4;

import com.snmwyl.oop.Demo11.Outer;

//一个项目应该只存一个main方法
public class Application {
    public static void main(String[] args) {
        Outer outer = new Outer();
        outer.out();   //我是外部类的一个方法。
        Outer.Inner1 inner = outer.new Inner1();   //通过外部类实例化内部类
        inner.in();   //我是内部类的一个方法。
        inner.getID();   //10
    }
}
posted @ 2025-12-21 23:15  神奈酱  阅读(3)  评论(0)    收藏  举报