面向对象(Object Orientation Programming)

Three characteristic of object orientation:

  1. Encapsulation: capturing data and keeping it safely and security from outside interfaces
    使用private关键之修饰成员变量,成员方法,被修饰的只能在本类中被使用
public class Student{
    private String name;
    private int age;
    
    // 每个成员变量对应的有一对setter、getter方法用来访问该成员变量
    // this代表所在类当前引用对象的地址值,也就是对象自己的引用
    public String getName(){
        reurn name;
    }
    publid void setName(String name){
        this.name = name;
    }
}

2.Inheritance: This is the process by which a class can be derived from a base class with all features of the base class and some of its own. This increases code reusability
Inheritance:主要解决共性抽取,是多态的前提,没有继承就没有多态
父类、基类、超类
子类、派生类
1.子类可以拥有父类的内容
2.子类还可以拥有自己的特性的内容
3.Java语言是单继承的
4.Java是可以多级集成的
5.一个父类可以有很多的子类

3.Polymorphism: This is the ability to exist in various forms. For example an operator can be overloaded so as to add two integer numbers and two floats and join two Strings.
使用多态的作用:
*1、无论new的时候换成是那个子类对象,等号左边的方法都不会变化,也就是不用管具体是什么类的方法
注意:
1、extends继承和implements实现是多态性的前提
2、在代码中表现为:父类引用指向子类对象,也就是左父右子

父类名称 对象名 = new 子类名称();
or
接口名称 对象名 = new 实现类名称();

多态的好处:父类类型作为方法的形式参数,但是将来调用方法的时候,传递的是子类的对象,用父类类型接收子类对象,使得不同的子类都可以作为这个方法的参数。而且多态规定:方法执行的时候不是父类的方法,而是经过子类重写的方法,也就是同一个方法可以根据不同的子类表现出不同的行为。

成员方法在继承中可以覆盖重写,看new的是谁,就优先使用谁的成员方法,没有就向上找
但是成员变量是不可以覆盖重写的,访问成员变量的2种使用方式
1、直接通过对象名访问成员变量,看等号左边是谁,就优先用谁的成员变量,没有就向上找
2、通过成员方法访问成员变量,看该方法属于谁,就访问的是谁的成员变量,没有还是向上找

原文地址:https://www.cnblogs.com/zhuobo/p/10598480.html