Java object-oriented three characteristics: inheritance, encapsulation, polymorphism

Java encapsulation, inheritance, polymorphic notes

1 package

1. Package naming rules

(1) Can only contain numbers, letters, underscores, and dots.

(2) cannot begin with a number,

(3) Cannot be keywords or reserved words

For example:

demo.class.exec1 //error class is a keyword

demo.12a //Error, start with a number

demo.ab12.oa // vs

Examples of naming conventions:

Generally lowercase letters + small dots (usually com.company name.project name.business module name)

for example:

com.hspedu.oa.model;

com.hspedu.oa.controller;

Example:
com.sina.crm.user//user module

com.sina.crm.order//order module

com.sina.crm.utils //tool ​​class


2. Commonly used packages

A package contains many classes. The commonly used packages in java are:

java.lang.* //lang package is the basic package, imported by default, no need to import again

java.util.* //util package, toolkit provided by the system, tool class, using Scanner

java.net.* //network package, web development

java.awt.* // is to do java interface development, GUI


3. Precautions for package introduction

There is at most one package in a class

The function of package is to declare the package where the current class is located. It needs to be placed at the top of the class. There is at most one package in a class.

2. Access modifiers

1. Basic introduction

Java provides four kinds of access control modifier symbols to control the access rights (range) of methods and attributes (member variables)

1. Publicity level: Modified with public, open to the public

2. Protected level: modified with protected, open to subclasses and classes in the same package

3. Default level: no modifiers, open to classes in the same package

4. Private level: Decorated with private, only the class itself can access it, not open to the public

insert image description here

3. Three characteristics of object-oriented programming: inheritance, encapsulation and polymorphism

1. Encapsulation

1.1 Definition of package

Encapsulation (encapsulation) is to encapsulate the abstracted data [attribute] and the operation [method] on the data together, the data is protected inside, and other parts of the program can only operate on the data through the authorized operation [method]. .

1.2 The trilogy of implementation steps of encapsulation

1)Privatize the attribute to private【The attribute cannot be modified directly】

2) Provide a public (public) set method for judging and assigning properties

public void setXxx(类型参数名){
    
    
//set方法用来设置或者修改属性值
//加入数据验证的业务逻辑属性=参数名;
}

3) Provide a public get method for obtaining the value of the attribute

public XX getXxx(){
    
    //权限判断
return xx;
}

1.3 Packaging Quick Start Case

Case number one:

It is not possible to check people's age, salary and other privacy at will, and to conduct reasonable verification of the set age.

If the age is reasonable, set it, otherwise the default 'age must be 1-120, age and salary cannot be directly checked, and the length of name is between 2-6

package com.hspedu.encap;
//不能随便查看人的年龄,工资等隐私,并对设置的年龄进行合理的验证。年龄合理就设置,否则给默认
//年龄必须在1-120,年龄,工资不能直接查看,name的长度在2-6之间
public class Encapsulation {
    
    
    public static void main(String[] args) {
    
    
        Person person = new Person();
        person.name="li";
        person.setAge(10);
        person.setSalary(10000);
        System.out.println(person.info());
    }
}
class Person{
    
    
    public String name;
    private int age;
    private double  salary;

    public void  setName(String name){
    
    
        if(name.length() >=2 && name.length() <=10)
            this.name = name;
        System.out.println("不合法");
    }
    public void setAge(int age) {
    
    
        if(age < 1 || age > 120)
            System.out.println("年龄不符合条件");
        this.age = age;
    }
    public void setSalary(double salary) {
    
    
        this.salary = salary;
    }
    public String getName(){
    
    
        return name ;
    }
    public int getAge() {
    
    
        return age;
    }
    public double getSalary() {
    
    
        return salary;
    }
    //写一个方法返回字符串
    public String  info(){
    
    
        return "信息为 name="+name+"age="+age+"salary="+salary;
    }
}

Case two:

Create a program, define two classes in it: Account and AccountTest classes, and experience the encapsulation of Java.

1. The Account class requires attributes: name (2-digit, 3-digit or 4-digit length), balance (must be >20), password (must be 6 digits), if not satisfied, a prompt message will be given, and a default value will be given

2. Assign values ​​to the properties of the Account through the setXxx method.

3. Test in AccountTest

Prompt knowledge points:
String name="";int len ​​= name.length();

package com.hspedu.encap;

public class Account{
    
    
    String name;
    double salary;
    String pass;

    public Account() {
    
    
    }

    public Account(String name, double salary, String pass) {
    
    
        this.name = name;
        this.salary = salary;
        this.pass = pass;
    }

    public String getName() {
    
    
        return name;
    }

    public double getSalary() {
    
    
        return salary;
    }


    public void setName(String name) {
    
    
        if(name.length() == 2 || name.length() == 3 || name.length() == 4)
            this.name = name;
    }

    public void setSalary(double salary) {
    
    

        if(salary >= 20){
    
    
            this.salary = salary;
        }else {
    
    
            this.salary = 0;
        }


    }

    public void setPass(String pass) {
    
    
        if(pass.length() == 6)
            this.pass = pass;
        else {
    
    
            System.out.println("密码错误");
            this.pass = "000000";
        }

    }

    public String getPass() {
    
    
        return pass;
    }

    public void showInfo(){
    
    
        System.out.println("name =" + name + "salary =" + salary + "pwd =" + pass);
    }
}
package com.hspedu.encap;

public class AccountTest {
    
    
    public static void main(String[] args) {
    
    
        Account account = new Account();
        account.setName("ping");
        account.setSalary(13);
        account.setPass("123456");
        account.showInfo();

    }
}

2. Inheritance

1. Basic introduction and schematic diagram of inheritance

Inheritance can solve code reuse and make our programming closer to human thinking. When multiple classes have the same attributes (variables) and methods, the parent class can be abstracted from these classes, in the parent class

These same properties and methods are defined in the class, and all subclasses do not need to redefine these properties and methods, they only need to declare the inheritance of the parent class through extends .

Draw a schematic diagram of inheritance

insert image description here

2. The basic grammar of inheritance

class 子类 extends 父类{
    
    }

1) The subclass will automatically have the properties and methods defined by the parent class

2) The parent class is also called the super class, the base class.

3) Subclasses are also called derived classes.

3. Focus on understanding

1. Subclasses inherit all properties and methods, non-private properties and methods can be directly accessed in subclasses, but private properties and methods cannot be directly accessed in subclasses, and must be accessed through public methods

to split

(1) The subclass inherits all properties and methods, non-private properties and methods can be directly accessed in the subclass, except for the private methods in the parent class that cannot be used after inheritance, and can be used with methods

father

package com.hspedu.extend_.improve;
//父类,是pupil和graduate的父类
public class Student {
    
    
    //共有的属性
    public String name;
    private  double score;
    public int age;
	//共有的方法
    public void setScore(double score) {
    
    
        this.score = score;
    }
    public void showInfo(){
    
    
        System.out.println(age + "岁的" + name + "考试考了" + score);
    }
}

Subclass: Assuming that only a certain information displayed is different, this information is unique to the subclass

package com.hspedu.extend_.improve;
public class Pupil extends Student {
    
    
    
    public void testInfo(){
    
    
        System.out.println("小学生" + name + "正在考小学数学");
    }
}
package com.hspedu.extend_.improve;

public class Graduate  extends Student{
    
    

    public void testInfo(){
    
    
        System.out.println("大学生"+ name + "正在考大学数学");
    }
}

test

package com.hspedu.extend_.improve;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Pupil pupil = new Pupil();
        pupil.name="li";
        pupil.age = 10;
        pupil.setScore(100);
        pupil.testInfo();
        pupil.showInfo();
        System.out.println("==============");
        Graduate graduate = new Graduate();
        graduate.name = "ping";
        graduate.age = 20;
        graduate.setScore(98);
        graduate.testInfo();
        graduate.showInfo();
    }
}

(2) But private properties and methods cannot be directly accessed in subclasses

The age just now is a common attribute

//如果把父类中年龄改成私有的
private int age;

//测试中的这一行代码会出错
  pupil.age = 10;

(3) Solve the above problems: access through public methods

package com.hspedu.extend_;

public class Base {
    
    
    //不同的属性
    public int n1 = 100;
    protected int n2 = 200;
    int n3 = 300;
    //n4是私有的,Sub无法直接拿到
    private  int  n4 = 400;
    //父类中提供了一个public的方法,返回了n4,通过这个方法,Sub类中就可以拿到n4的参数
    public int getN4() {
    
    
        return n4;
    }
    //无参构造器
    public Base(){
    
    
        System.out.println("父类的无参构造器Base()被调用....");
    }
    //不同的属性
    public void Base1(){
    
    
        System.out.println("Base1()...");
    }
    void Base02(){
    
    
        System.out.println("Base2()...");
    }
    protected void  Base03(){
    
    
        System.out.println("Base03()...");
    }
    //在Sub中是无法获取的
    private void Base4(){
    
    
        System.out.println("Base4()....");
    }
    //可以通过这个方法来实现
    public void callBase4(){
    
    
        Base4();
    }
}

test

package com.hspedu.extend_;

public class Sub extends  Base{
    
    
     public Sub(){
    
    
//         super();//默认调用父类的无参构造器,写不写都会被调用
         System.out.println("子类的无参构造器Sub()被调用...");
     }
     public void ok(){
    
    
         System.out.println("n1:"+ n1+ "\t n2:" + n2 + "\t n3:" + n3);
         //由于Base下的n4是私有的,因此无法直接拿到,但是可以将私有的属性通过共有的方法让继承后类中使用

         System.out.println("n4:"+getN4());
         Base1();
         Base02();
         Base03();
         //Base4的方法是私有的无法拿到,但是可以通过共有的方法那它在传到当前位置来
         //Base4();
         //在Base中使用了公共方法将其传入
         callBase4();

     }
}

2. The subclass must call the constructor of the parent class to complete the initialization of the parent class

 //尽管Sub类中的方法没有调用父类的无参构造器,但是也会显示父类无参构造器相关信息,然后显示子类的无参构造器相关信息
//上面代码的片段
public class Sub extends  Base{
    
    
     public Sub(){
    
    
//         super();//默认调用父类的无参构造器,写不写都会被调用
         System.out.println("子类的无参构造器Sub()被调用...");
     }

     public Sub(String name ){
    
    
         System.out.println("子类有参构造器Sub(String name )被调用");

     }
}

test:
insert image description here

3. When creating a subclass object, no matter which constructor of the subclass is used, the no-argument constructor of the parent class will always be called by default. If the parent class does not provide a no-argument constructor, it must be in

Use super in the constructor of the subclass to specify which constructor of the parent class is used to complete the initialization of the parent class, otherwise, the compilation will not pass [example]

package com.hspedu.extend_;

public class Extendtail {
    
    
    public static void main(String[] args) {
    
    

        //尽管Sub类中的方法没有调用父类的无参构造器,但是也会显示父类无参构造器相关信息,然后显示子类的无参构造器相关信息
        Sub sub = new Sub();
        System.out.println("============");
        Sub sub1 = new Sub();
//       sub.ok();
    }
}

Test result: the default parent class no-argument constructor will be called

insert image description here


specify call constructor

public class Base {
    
    
    
    //无参构造器
//    public Base(){
    
    
//        System.out.println("父类的无参构造器Base()被调用....");
//    }
    public  Base(String name, int age){
    
    
        System.out.println("用的是父类第二个Base(String name, int age)");
    }
}
public class Sub extends  Base{
    
    
     public Sub(){
    
    
//         super();//默认调用父类的无参构造器,写不写都会被调用
         //当父类的无参构造器被覆盖时,需要指定
         //super在使用时,必须放在构造器的第一行
         //super()和this()都只能放在构造器的第一行,因此这两个方法不能共存在一个构造器里面,第一行写了super(),就不能写this()
         super("li",10);
         System.out.println("子类的无参构造器Sub()被调用...");
     }

     public Sub(String name ){
    
    
           //当父类的无参构造器被覆盖时,需要指定
         super("chen",24);
         System.out.println("子类有参构造器Sub(String name )被调用");

     }

insert image description here

4. If you want to specify to call a constructor of the parent class, then call it explicitly: super(parameter list)

5. When super is used, it must be placed in the first line of the constructor (super)

6. Both super() and this() can only be placed in the first line of the constructor, so these two methods cannot coexist in a constructor

7. All classes in java are subclasses of the Object class, and Object is the base class of all classes.

8. The call of the parent class constructor is not limited to the direct parent class! It will be traced all the way up to the Object class (top-level parent class)

9. A subclass can only inherit at most one parent class (referring to direct inheritance), that is, a single inheritance mechanism in java.

Thinking: How to let class A inherit class B and class C?

Answer: A inherits from B, and B inherits from C

The essence of inheritance:

/*
* (1)先查看子类是否有该属性
* (2)如果子类有该信息,并且可以访问,则返回信息
* (3)如果子类没有该属性,就看父类有没有这个属性,如果父类有该属性,并且可以访问,则返回父类的该信息
* (4)如果父类的该属性不可以访问,继续找上一级的父类,直到找到object
* */

insert image description here

Question: If the object son wants to access the attribute of age, but the age of the parent class Father is private, and the age of the grandpa class Grandpa is shared, can he get the age of grandpa?

cannot! Because son has already found the age attribute when accessing the Father class, but because it is private and has no right to access, the result cannot be obtained. It has already been found, so I don’t want to look for it anymore, and I don’t say that I don’t have the right to access it and get the age attribute in the grandpa class directly.

4. super keyword

super represents a reference to the parent class, used to access the properties, methods, and constructors of the parent class

●Basic grammar

1. Access the properties of the parent class, but not the private properties of the parent class [case] super. property name;

2. To access the method of the parent class, you cannot access the private method of the parent class [case] super. method name (parameter list);

3. Access the constructor of the parent class (this has been used before): super (parameter list); can only be placed in the first sentence of the constructor, and only one sentence can appear!

insert image description here
Super keyword
1. The benefits of calling the constructor of the parent class (the division of labor is clear, the properties of the parent class are initialized by the parent class, and the properties of the subclass are initialized by the subclass) 2. When there are members
in the subclass and members of the parent class (properties and methods ) with the same name, in order to access the members of the parent class, you must pass super. If there is no duplicate name, using super, this, and direct access has the same effect!
3. The access of super is not limited to the direct parent class. If there are members with the same name in the grandpa class and this class, you can also use super to access the members of the grandpa class ; If there are members with the same name in multiple base classes, use super access to follow the principle of proximity. A->B->C, of ​​course, also need to abide by the rules related to access rights

5.Super and this key

insert image description here

3. Rewrite/overwrite

Simply put: method overriding (overriding) means that the subclass has a method that has the same name, return type, and parameters as a method of the parent class, then we say that the method of the subclass overrides the method of the parent class

1. The parameters and method names of the subclass methods should be exactly the same as the parameters and method names of the parent class methods.

2 The return type of the subclass method is the same as the return type of the parent class method, or a subclass of the parent class return type

For example, the return type of the parent class is Object, and the return type of the subclass method is String

【Demo】

public class Animal {
    
    
    public void ask(){
    
    
        System.out.println("动物在叫唤.....");
    }
    public Object m1(){
    
    
        return null;
    }
}
public class Dog extends Animal {
    
    

    public void cry(){
    
    
        System.out.println("wangwang......");
    }
    //和public object m1()构成重写
    public String m1(){
    
    
        return null;
    }
}

【Exercise 1】:

1. Write a Person class, including attributes private (name, age), constructor, method say (returns a string of self-introduction).
2. Write a Student class, inherit the Person class, add id, score attribute private, and a constructor, define the say method (return self-introduction information).
3. In main, create Person and Student objects respectively, and call the say method to output self-introduction.
Experience the benefits of using super() in subclasses
1. Person class, parent class

package com.hspedu.override_;
public class Person {
    
    
    private  String name;
    private int age;
    
    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }
    public String  say(){
    
    
        return "我的名字是"+ name + "年龄是:" + age;
    }

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

    public void setAge(int age) {
    
    
        this.age = age;
    }

    public String getName() {
    
    
        return name;
    }

    public int getAge() {
    
    
        return age;
    }
}

2.studen class

package com.hspedu.override_;

public class Student extends Person {
    
    
    private  int id;
    private  double score;

    public Student(String name, int age, int id, double score) {
    
    
        super(name, age);
        this.id = id;
        this.score = score;
    }
    public String say(){
    
    
        return super.say() + "id= "+ id + "score = " +score;
    }
    public void setId(int id) {
    
    
        this.id = id;
    }

    public void setScore(double score) {
    
    
        this.score = score;
    }

    public int getId() {
    
    
        return id;
    }

    public double getScore() {
    
    
        return score;
    }
}

3. Test

package com.hspedu.override_;
public class MainT {
    
    
    public static void main(String[] args) {
    
    
        Person person = new Person("li",18);
        System.out.println(person.say());
        System.out.println("====");
        Student student = new Student("li",18,2203,80);
        System.out.println(student.say());

    }
}

Guess you like

Origin blog.csdn.net/qq_41977843/article/details/128155501