Three major characteristics of Java --- encapsulation, inheritance, polymorphism

Three major characteristics of Java-encapsulation, inheritance, polymorphism

One, packaging

After learning the previous content, we generally don't care about attribute modifiers, right? At most, write a public modifier, but most of them are the default. But it is not recommended for everyone, why? Let's take a look at the following
Dog dog = new Dog();
dog.health =-99999;
Insert picture description here
Considering security and permissions, attributes cannot be assigned and changed at will. Therefore, the introduction of packaging.
The concept of packaging:
Insert picture description here
For example: it is the express package box in life, in order to protect privacy and safety.
Specific steps:
Insert picture description here
code implementation

public class Pet {					//创建Pet类,下面全都改为private 修饰的属性
    private String name;
    private String petType;
    private int healthValue;
    private String gender;
    private int intimacy;

    public void introduce(){
        System.out.println("我的名字叫"+this.getName()+",健康值为:"+this.getHealthValue()+",和主人的亲密度为"+this.getIntimacy()+",我的性别是"+this.getGender());
    }

    public String getName() {				//这些就是getter方法
        return name;
    }

    public void setName(String name) {		//这些就是setter方法,快捷键【Alt+Insert】
        this.name = name;
    }

    public String getPetType() {
        return petType;
    }

    public void setPetType(String petType) {
        this.petType = petType;
    }

    public int getHealthValue() {
        return healthValue;
    }

    public void setHealthValue(int healthValue) {				//定义规范
        if(healthValue<0||healthValue>100){
            System.out.println("输入不合法");
            this.healthValue = 60;
        }else {
            this.healthValue = healthValue;
        }
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        if(null==gender ||"公".equals(gender)){
            this.gender = "公";
        }else {
            this.gender = gender;
        }
    }

    public int getIntimacy() {
        return intimacy;
    }

    public void setIntimacy(int intimacy) {
        if(intimacy<0||intimacy>100){
            System.out.println("输入不合法");
            intimacy = 20;
        }
        this.intimacy = intimacy;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Pet pet = new Pet();
        System.out.println("请输入宠物的名字:");
        String name =sc.next();
        pet.setName(name);
        System.out.println("请选择宠物的类型:(1.狗狗 2.企鹅)");         //写在setter外面的
        int type =sc.nextInt();
        if(type==1){
            pet.setPetType("狗狗");
        }else {
            pet.setPetType("企鹅");
        }
        System.out.println("请选择"+pet.petType+"的性别:1.Q仔2.Q妹");
        int genderChoice = sc.nextInt();
        if(genderChoice==1){
            pet.setGender("Q仔");
        }else {
            pet.setGender("Q妹");
        }
        System.out.println("请输入"+pet.getPetType()+"的健康值");      //写在setter里面的
        pet.setHealthValue(sc.nextInt());

        System.out.println("请输入"+pet.getPetType()+"的亲密度");
        pet.setIntimacy(sc.nextInt());

        pet.introduce();
    }
}

Although the code looks a lot, it is actually very simple, just a few properties, plus a bunch of getter and setter methods.

Then comes the bag, pay attentionpackage package name; all lowercase, should be written in the first line of the code
Insert picture description here
Why introduce the concept of package, pay attention to the previous chapter, the permissions of modifiers.
Of course, if you want to introduce a package, you need to use keywordsimport package name. class nameorimport package name.*, This is written under the package
, did you notice when writing Scanner before this?

Second, inheritance

In Java, we useextendsKeywords to express inheritance relationship
, like:
class A{ attribute method... } class B



extendsA{ attribute method... } We call A the parent class of B, and B the subclass of A. Then why do we use inheritance? Extract some common codes to form a parent class, and unique ones as subclasses, so that it is convenient for code modification and the creation of duplicate codes. Pay attention here





Insert picture description here

A class can only inherit one parent class, but a parent class can have multiple subclasses, This is easy to understand.
Insert picture description here
There are two points to note here:
1:superAnd what I said beforethisAlmost one refers to the parent class, and one refers to this class (the current object).
2: Inheritance means that the subclass has all the things of the parent class. As for the properties modified by private cannot be accessed, they are actually hidden. Later, reflection can be accessed, and there isstatic (static variable: class variable), It belongs to the class itself, it does not belong to a single object, so it cannot be accessed either.
The construction method under inheritance conditions
Insert picture description here
Here you can take a look at the article about the constructor, static method, and execution order reproduced earlier.

Finally, let's talk about inheritance through an example

/**
 * @Author shall潇
 * @Date 2021/1/19
 * @Description
 */
 //Car类
class Car {
    private int site = 4;  //座位数
    Car(){
        System.out.println ("载客量是"+site+"人");
    }
    public void setSite(int site){
        this.site = site;
    }
    void print(){
        System.out.print("载客量是"+site+"人");
    }

    public static void main(String[] args) {
        Bus bus = new Bus(20);
        bus.print();
    }
}
//Bus类继承Car类
class Bus extends Car{
    Bus(int site){
        setSite(site);
    }
}

The results show that the
Insert picture description here
first 4 people called the constructor of the parent class, but the parameter 20 was not used, but the default value of the parent class itself was used. The
second 20 people called the print method of the parent class. Parameter 20 is used at this time

Three, polymorphism

The core of polymorphism is actually overload and rewrite
Four manifestations of polymorphism: overloading, rewriting, abstract class, interface

1. Overload

In a class (in fact, this is not necessary, this condition is necessary when there is no subclass),Same method name, different parameter list. It has nothing to do with other things. It is automatically matched with different methods according to the type and number of incoming parameters.
[Special: In subclasses, you can also implement the method overloading of the parent class]

[Let’s give a special example, I won’t give an example if it’s a formal one, you can try it yourself]
Parent class: Pet, method in the parent class: getPet method
Insert picture description here
Sub class: Cat
Insert picture description here
Pay attention to the flags in front of these two methods in the subclass. The first one does not have an overridden flag, but no error is reported, indicating that it is overloaded, and the second has.
The method name is the same as the parent class, and the parameter list is different, but even though the method is in a different class, it is also overloaded.

2. Rewrite

To be in a different class, generally rewrite the parent class method in the subclass. The method name remains the same, the parameter list has not changed, but the method internally has changed.

[Overload rules]

The method name is the same, the
parameter list is the same, the
return value type is the same or its subclass, the
access rights cannot be stricter than that of the
parent class. The static method of the parent class cannot be overridden by the subclass as a non-static method, and the non-static method of the parent class cannot be overridden by the subclass as a static method
. A class can define a static method with the same name as the parent class, so as to hide the static method of the parent class in the subclass (Note: super cannot be used in the static method)
The private method of the parent class cannot be overridden by the subclass and
cannot be thrown more than the parent class method The exception

[For example] the
parent class, the parent class method: show

public class Pet {
    private String name;
    private int health;
    private int love;

    public String getName() {
        return name;
    }

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

    public int getHealth() {
        return health;
    }

    public void setHealth(int health) {
        this.health = health;
    }

    public int getLove() {
        return love;
    }

    public void setLove(int love) {
        this.love = love;
    }

    public String show(){		//这里要被重写
        return "我叫:"+this.name+"我的健康值:"+this.health+"爱心值为:"+this.love;
    }
    
    public Pet getPet(){
        return new Pet();//返回一个Pet对象
    }
}

Subclass, subclass method: show

public class Cat extends Pet{
    private String strain; 		//多了一个 品种属性

    public String getStrain() {
        return strain;
    }

    public void setStrain(String strain) {
        this.strain = strain;
    }

    public String show(){    	   //方法重写
        String s = super.show();	//先调用父类 的show方法
        return s+"品种为"+this.strain;//再加入自己的属性
    }

    public Pet getPet(String name){
        return null;
    }

    public Pet getPet(){
        return new Pet();
    }
}

Test class

public static void main(String[] args) {
        Cat cat = new Cat();
        cat.setName("葡萄");
        cat.setHealth(76);
        cat.setLove(67);
        cat.setStrain("暹罗猫");

        System.out.println(cat.show());

The results show that
Insert picture description here
since we can rewrite the methods defined by ourselves, can we rewrite the Java methods?
Of course it is possible, for example: the toString, equals, getClass, hashcode and other methods in the object class (it is the parent class of all classes).
Next, let's take the rewrite equals method as an example to define our own comparison standard.
[Here we define two cats are the same if they are the same breed]
Sub-category: Cat
Insert picture description here
test category

Cat cat = new Cat();
cat.setName("葡萄");
cat.setHealth(76);
cat.setLove(67);
cat.setStrain("暹罗猫");

Cat cat1 = new Cat();
cat1.setName("豆豆");
cat1.setHealth(26);
cat1.setLove(37);
cat1.setStrain("暹罗猫");

System.out.println(cat.equals(cat1));

Output results
Insert picture description here
After the rewriting, we formally enter polymorphism.
Before we start, let me throw a brick: Can a big box hold small things, and can a small box hold big things? Is it comfortable to wear a big box or a small box?
Now we want to define a master human: Master, the only method of taking a pet to see a doctor is the master human. Note that we are writing about pets here, not certain.
Master class

public class Master {
    public void cure(Pet p){		//注意看参数类型
        p.toHospital();				//之前的Pet类中没有这个方法,我们添加一下
    }
}

Pet class

public void toHospital(){
        System.out.println("父类去医院");//当然,子类在重写后,会覆盖掉
}

Cat class

@Override							//重写父类的看病方法
public void toHospital() {
    if(this.getHealth()<50){
        System.out.println("猫咪生病了,建议给猫咪看病");
        setHealth(60);
    }else {
        System.out.println("您的猫咪很健康");
    }
}

Test class

Cat cat1 = new Cat();
cat1.setName("豆豆");
cat1.setHealth(26);
cat1.setLove(37);
cat1.setStrain("暹罗猫");

Master master = new Master();
master.cure(cat1);

The results show
Insert picture description here
that as far as the Master is concerned, no matter what kind of cat or dog you are, as long as you inherit the Pet class, you can come to me. As long as you come in, I will take you to the doctor.

Is that all about polymorphism? of course not
Polymorphism: The subclass object references the parent type Pet p = new Cat();
The shape like this is the real use of polymorphism. Why write it like this? Let's continue to look down:
In fact, the above sentence means: creating a Pet type of Cat object, you may be confused again, in fact, it is the big box mentioned above to load small things, let's take an example of the
Cat class

public void catchMouse(){
        System.out.println("抓老鼠");		//加了一个子类独有的方法
    }

Test class

Pet p2 = new Cat();
p2.setName("fofo");
p2.setHealth(78);
p2.setLove(56);
((Cat) p2).setStrain("加拿大无毛猫");	//调用子类特有的属性
 ((Cat) p2).catchMouse();			//调用子类特有的方法

The output is to catch mice.
We can notice. When we create a Pet type of Cat object, we need to force a type conversion when we want to call a unique method in the Cat class. You may have doubts, why not directly create Cat type objects, of course, to think more directly. I only need the Pet type. I don't need any cats or dogs. All of them are Pet types. When I need your unique method, I will switch the type.

Of course, what if it is not an inheritance relationship?
Then we passinstanceofKeyword to determine whether it is an inheritance relationship.
For example:

if(p2 instanceof Cat)
    ((Cat) p2).catchMouse();

Guess you like

Origin blog.csdn.net/qq_43288259/article/details/112799914