The fourteenth day of Java basic learning (encapsulation, inheritance, polymorphism)

1. Packaging

1. Three major characteristics of object-oriented: encapsulation, inheritance, polymorphism

2. Permission modifiers: Permission modifiers control the visible range of variables.
public: public, public modified member variables or methods can be directly accessed by anyone.
private: private, privately modified member variables or methods can only be accessed directly in this class.

3. Encapsulation steps
① Use private to modify the properties that need to be encapsulated.
② Provide a public method to set or get the private member property.
set property name(); [set property]
get property name(); [get property]

4. Question: Does the package have to provide get or set methods?
Not necessarily, it depends on demand.

5. Specification: In real development, all member attributes (member variables) of general entity classes must be encapsulated.
Entity class: An entity class is used to describe a class of things and is called an entity class.

6. The benefits of encapsulation: improve data security, simple operation, hidden implementation

 class MyMember{    
    public  String name; //名字
    private String sex; //性别
    public  int salary; //薪水        

    //定义一个公共的方法设置sex属性
    public void setSex(String s){
        if (s.equals("男")||s.equals("女")){ //注意:如果比较两个字符串的内容是否一致,不要使用==比较,使用equals方法。
            sex = s;
        }else{
            //默认是男
            sex = "男";
        }
    }
    //定义一个公共的方法获取sex属性
    public String getSex(){
        return sex;
    }

    //聊天
    public void talk(){
        System.out.println(name+"聊得非常开心");
    }
}

class Demo14.1{
    public static void main(String[] args){
        MyMember m = new MyMember();
        m.name="李四";
        m.setSex("女");
        m.salary  = 8000;
        System.out.println("姓名:"+ m.name+" 性别:"+ m.getSex()+" 薪水:"+ m.salary);
    }
}

7. Requirements: Use java class to describe a calculator class. The calculator has three public properties of operand 1, operand 2, and operator, and also has the functional behavior of calculation. Requirement: The properties of operand 1, operand 2, and operator cannot be directly assigned, and must be encapsulated. (+ - * / )

//计算器类
class Calculator{
    private int num1; //操作数1
    private int num2;  //操作数2 
    private char option ; //运算符 

    //提供公共的方法设置属性值....                  
    public void initCalculator(int n1 , int n2 , char op){ //初始化计算器
        num1 = n1;
        num2 = n2;
        if(op=='+'||op=='-'||op=='*'||op=='/'){
            option = op;
        }else{
            option = '+';   
        }   
    }
    //计算的功能
    public void calculate(){
        switch(option){
            case '+':
                System.out.println("做加法运算,结果是:"+(num1+num2));
                break;
            case '-':
                System.out.println("做减法运算,结果是:"+(num1-num2));
                break;
            case '*':
                System.out.println("做乘法运算,结果是:"+(num1*num2));
                break;
            case '/':
                System.out.println("做除法运算,结果是:"+(num1/num2));
                break;
        }
    }
}
class Demo14.2{
    public static void main(String[] args){
        //创建了一个计算器对象
        Calculator c = new Calculator();
        //设置属性值
        c.initCalculator(1,2,'+');
        //调用计算器的计算功能
        c.calculate();
    }
}

2. Inheritance

1. Common relationships between classes (the relationship between the whole and the part)

//球员类
class Player{   
    int num; //编码
    String name;
    public Player(int num , String name){
        this.num = num;
        this.name = name;
    }
    public void run(){
        System.out.println(name+"开跑...");
    }
}
//球队类
class Team{
    String name;  //球队的名字
    Player p1;  //球员1 
    Player p2;  //球员2
    Player p3;  //球员3
    public  Team(String name,Player p1,Player p2,Player p3){
        this.name = name;
        this.p1 = p1;
        this.p2 = p2;
        this.p3 = p3;
    }   
    //开始比赛
    public void startGame(){
        System.out.println(name+"开赛啦!!");
    }
}
class Demo14.3{
    public static void main(String[] args){
        Player p1 = new Player(12,"梅西");
        Player p2 = new Player(7,"C罗");
        Player p3 = new Player(11,"内马尔");
        //球队
        Team t = new Team("恒大",p1,p2,p3);
        t.startGame();      
        System.out.println("名字:"+ t.p2.name);
    }
}

2. Inheritance: Inheritance is reflected by the keyword extends.

3. Inherited format

class 类名1 extends 类名2{

    }

4. Matters needing attention in inheritance:
① Do not inherit in order to reduce repetitive code, only inherit when there is a real inheritance relationship
② The private members of the parent class cannot be inherited.
③ The constructor of the parent class cannot be inherited.
④ When creating a subclass object, the constructor without parameters of the parent class will be called by default.

//人类 
class Person{
    String name;
    private int age;
    public  Person(String name){
        this.name = name;
    }
    public Person(){
        System.out.println("Person类的构造方法被调用了....");
    }
    public void eat(){
        System.out.println(name+"在吃饭...");
    }
}
//学生类
class Student extends Person {  // Student称作为Person类的子类,Person类就称作为Student的父类(超类、基类)
    int num; //学号
    public Student(){
        System.out.println("Student类的构造方法被调用了....");
    }
    public void study(){
        System.out.println(name+"好好学习!");
    }   
}
class Demo14.4{
    public static void main(String[] args){
        Student s = new Student();      
        s.name = "狗娃";
        System.out.println("名字:"+ s.name);
        s.eat();
    }
}

5. Calling the constructor of the parent class can initialize the properties inherited from the parent class.

class Fu{   
    int x = 10;
    String name;
    public Fu(String name){
        this.name = name;
        System.out.println("Fu类d带参的构造方法...");
    }
    public Fu(){
        System.out.println("Fu类无参的构造方法...");
    }
}
class Zi extends Fu{
    int x = 20;
    public Zi(String name){
        super(name); //指定调用父类一个参数的构造函数。
    }
    public void print(){
        System.out.println("x1 = "+ x);
    }

}
class Demo14.5{
    public static void main(String[] args){
        Zi z = new Zi("大头儿子"); 
        System.out.println("name= "+z.name);
    }
}

6, super keyword
① The super keyword represents the reference of the parent class space.
② The function of super keyword
◆ When there is a member with the same name in the child and parent class, the default is to access the members of the subclass in the subclass, and the members of the parent class can be specified through the super keyword.
◆ When a subclass object is created, the constructor without parameters of the parent class will be called first by default, and the constructor of the parent class can be called by specifying the super keyword.
③ Points to note when calling the superclass constructor with the super keyword
◆ If the subclass constructor does not specify to call the superclass constructor, the java compiler will add a super() statement to the subclass constructor.
◆ When the super keyword calls the constructor of the superclass, the statement must be the first statement in the constructor of the subclass.
◆ super and this keywords cannot appear in the same constructor to call other constructors at the same time. Because both statements require the first statement.
④ The difference between super keyword and this keyword
◆ The things represented are inconsistent.
The super keyword represents a reference to the parent class space. The this keyword represents the caller object of the owning function.
◆ The premise of use is inconsistent.
The super keyword must have an inheritance relationship before it can be used. The this keyword can be used without an inheritance relationship.
◆ The difference between calling the constructor The
super keyword is calling the constructor of the parent class. The this keyword is to call the constructor of this class.

7. Method rewriting
① The premise of method rewriting: There must be an inheritance relationship.
② Method rewriting: The child and parent class has a function with the same name, which we call method rewriting.
③ When to use method rewriting: When the function of the parent class cannot meet the needs of the subclass.
④ Matters needing attention in
method rewriting: ◆ When rewriting a method, the method name and the formal parameter list must be consistent.
◆ When the method is overridden, the permission modifier of the subclass must be greater than or equal to the permission modifier of the parent class.
◆ When the method is overridden, the return value type of the subclass must be less than or equal to the return value type of the parent class.
◆ When the method is overridden, the exception type thrown by the subclass should be less than or equal to the exception type thrown by the superclass.
Exception (worst), RuntimeException (little bad)
⑤ Requirements for method overloading
◆ Function names should be consistent.
◆ The formal parameter list is inconsistent (the number of formal parameters or the types of formal parameters are inconsistent)
◆ It has nothing to do with the return value type.

class Animal{}  //大的数据类型 
class Fish extends Animal{}  //小的数据类型
class Fu{
    String name;
    public Fu(String name){
        this.name = name;
    }
    public Animal eat() throws RuntimeException {
        System.out.println(name+"吃番薯...");
        return new Animal();
    }
}
class Zi extends Fu{
    String num; 
    public Zi(String name){
        super(name);//指定调用父类带参的构造方法
    }
    //重写父类的eat方法
    public Animal eat() throws Exception{
        System.out.println("吃点开胃菜..");
        System.out.println("喝点汤....");
        System.out.println("吃点龙虾....");
        System.out.println("吃青菜....");
        System.out.println("喝两杯....");
        System.out.println("吃点甜品...."); 
        return new Animal();
    }
}
class Demo14.6{
    public static void main(String[] args){
        Zi z = new Zi("大头儿子");
        z.eat();    
    }
}

8. The instanceof keyword
① Function: Determine whether an object belongs to a specified category.
② Prerequisites for use: There must be an inheritance or implementation relationship between the judged object and the specified category.
③ Use format: Object instanceof category
④ Function: Polymorphism. Generally, we will use this keyword to judge before doing forced type conversion, and then perform the conversion.

class Animal{
    String name;
    String color;
    public Animal(String name, String color){
        this.name = name;
        this.color = color;
    }
}
//狗是属于动物中一种
class Dog extends Animal {
    public Dog(String name,String color){
        super(name,color); //指定调用父类两个 参数的构造函数。
    }
    public void bite(){
        System.out.println(name+"咬人!!");
    }
}
//老鼠也是属于动物中一种
class Mouse extends Animal{ 
    public Mouse(String name,String color){
        super(name,color);
    }   
    public void dig(){
        System.out.println(name+"打洞..");
    }
}
class Demo14.7{
    public static void main(String[] args){
        Dog d = new Dog("哈士奇","白色");
        System.out.println("狗是狗类吗?"+(d instanceof Dog));//true
        System.out.println("狗是动物类吗?"+(d instanceof Animal));//true
        System.out.println("狗是老鼠类吗?"+ (d instanceof Mouse));=//报错
        Animal a = new Animal("狗娃","黄色"); 
        System.out.println("动物都是狗吗?"+ (a instanceof Dog));//false
    }
}

9.
The usage of the final keyword:
① When the final keyword modifies a variable of a basic type, the variable cannot be reassigned, and the first value is final.
② When the fianl keyword modifies a reference type variable, the variable cannot point to a new object again.
③ When the final keyword modifies a function, the function cannot be rewritten.
④ When the final keyword modifies a class, the class cannot be inherited.

The modifiers of constants are generally: public static final

//圆形
class Circle{
    double r; //半径
    public static final double PI = 3.14; //固定不变的
    public Circle(double r){
        this.r = r;
    }
    //计算面积
    public final void getArea(){
        System.out.println("圆形的面积是:"+r*r*PI);
    }
}
class Demo14.8 extends Circle{  
    public Demo14.8(double r){
        super(r);
    }
    public static void main(String[] args){
        final Circle c = new Circle(4.0);
        test(c);

        Demo14.8 c = new Demo14.8(4.0);
        c.getArea();
    }   
    public static void test(Circle c){
        c = new Circle(5.0);  //c变量又重新指向了新的对象。
        c.getArea();
    }
}

3. Polymorphism

1. Polymorphism: An object has multiple forms (the reference type variable of the parent class points to the object of the subclass), or the reference type variable of the interface points to the object of the interface implementation class)

2. The premise of polymorphism: There must be an inheritance or implementation relationship.

3. Details to be paid attention to in
polymorphism ① In the case of polymorphism, when there is a member variable of the same name in the child and parent class, the member variable of the parent class is accessed.
② In the case of polymorphism, when there is a non-static member function of the same name in the child and parent class , the member function of the subclass is accessed.
③ In the case of polymorphism, when there is a static member function with the same name in the sub-parent class, the member function of the parent class is accessed.
④ In the case of polymorphism, the unique member of the subclass cannot be accessed
①②③ Summary : In the case of polymorphism, when there is a member with the same name in the sub-parent class, all the members of the parent class are accessed, except when the non-static function with the same name is used to access the sub-class.

4. Look on the left when compiling, not on the right when running.
Compile to the left: When the java compiler compiles, it will check whether the class to which the reference type variable belongs has the specified member, and if it does not have the specified member, it will compile an error immediately.

//动物类
abstract class Animal{
    String name;
    String  color = "动物色";
    public Animal(String name){
        this.name = name;
    }
    public abstract void run();
    public static void eat(){
        System.out.println("吃得很开心..");
    }
}
//老鼠
class  Mouse extends Animal{
    String color = "黑色";
    public Mouse(String name){
        super(name);
    }   
    public void run(){
        System.out.println(name+"四条腿慢慢的走!");
    }
    public static void eat(){
        System.out.println("老鼠在偷吃..");
    }
    //老鼠特有方法---打洞
    public void dig(){
        System.out.println("老鼠在打洞..");
    }
}
class Fish extends Animal {
    public Fish(String name){
        super(name);
    }   
    public  void run(){
        System.out.println(name+"摇摇尾巴游..");
    }
}
class Demo14.9{
    public static void main(String[] args){
        //多态:父类的引用类型变量指向子类的对象
        Animal a = new Mouse("老鼠");
        System.out.println(a.color);//动物色
        a.dig();
        //a.eat();
    }   
}

5. Application
of polymorphism ① When polymorphism is used for formal parameter types, it can receive more types of data.
② When polymorphism is used to return value types, more types of data can be returned.

6. The benefits of polymorphism: Improve the scalability of the code.

//需求: 定义一个函数可以接收任意类型的图形对象,并且打印图形面积与周长。

//图形类
abstract class MyShape{
    public abstract void getArea();
    public abstract void getLength();   
}
class Circle extends MyShape{//圆形
    public static final double PI = 3.14;
    double r;
    public Circle(double r){
        this.r =r ; 
    }
    public void getArea(){
        System.out.println("圆形的面积:"+ PI*r*r);
    }
    public void getLength(){
        System.out.println("圆形的周长:"+ 2*PI*r);
    }
}
class Rect extends MyShape{//矩形
    int width;
    int height;
    public Rect(int width , int height){
        this.width = width;
        this.height = height;
    }
    public void getArea(){
        System.out.println("矩形的面积:"+ width*height);
    }
    public void getLength(){
        System.out.println("矩形的周长:"+ 2*(width+height));
    }
}
class Demo14.10{
    public static void main(String[] args){
        Circle c = new Circle(4.0);
        print(c);
        Rect r = new Rect(3,4);
        print(r);

        MyShape m = getShape(0); //调用了使用多态的方法,定义的变量类型要与返回值类型一致。
        m.getArea();
        m.getLength();
    }
    //需求1:定义一个函数可以接收任意类型的图形对象,并且打印图形面积与周长。
    public static void print(MyShape s){ 
        s.getArea();
        s.getLength();
    }
    // 需求2:定义一个函数可以返回任意类型的图形对象。
    public static MyShape getShape(int i){
        if (i==0){
            return new Circle(4.0);
        }else{
            return new Rect(3,4);
        }
    }
}

7. Under current polymorphism, subclass-specific members cannot be accessed. If you need to access subclass-specific members, type coercion is required.
The most common problem of type conversion: java.lang.ClassCastException. Casting failed.

//动物类
abstract class Animal{
    String name;
    public Animal(String name){
        this.name = name;
    }
    public abstract void run();
}
//老鼠
class Mouse extends Animal{
    public Mouse(String name){
        super(name);
    }   
    public  void run(){
        System.out.println(name+"四条腿慢慢的走!");
    }
    //老鼠特有方法---打洞
    public void dig(){
        System.out.println("老鼠在打洞..");
    }
}
//鱼
class Fish extends Animal{
    public Fish(String name){
        super(name);
    }
    public void run(){
        System.out.println(name+"摇摇尾巴游啊游 !");
    }
    //吹泡泡
    public void bubble(){
        System.out.println(name+"吹泡泡...!");
    }
}
class Demo14.11{
    public static void main(String[] args){
        Animal a = new Mouse("老鼠");  //多态
        //调用子类特有的方法
        Mouse m  = (Mouse)a;  //强制类型转换
        m.dig();

        Mouse m = new Mouse("米老鼠");
        Fish f = new Fish("草鱼");
        print(f);
    }
    //需求: 定义一个函数可以接收任意类型的动物对象,在函数内部要调用到动物特有的方法。
    public static void print(Animal a){
        if(a instanceof Fish){
            Fish f = (Fish)a;
            f.bubble();
        }else if(a instanceof Mouse){
            Mouse m = (Mouse)a;
            m.dig();
        }
    }
}

8. Polymorphism under implementation relationship: interface variable = object of new interface implementation class

interface Dao{  //接口的方法全部都是非静态的方法
    public void add();
    public void delete();
}
//接口的实现类
class UserDao implements Dao{   
    public void add(){
        System.out.println("添加员工成功!!");
    }
    public void delete(){
        System.out.println("删除员工成功!!");
    }
}
class Demo14.12{
    public static void main(String[] args){
        //实现关系下的多态
        Dao d = new UserDao(); //接口的引用类型变量指向了接口实现类的对象
        d.add();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325992546&siteId=291194637