Java Series - Introduction to Encapsulation, Inheritance, and Polymorphism

Table of contents

I. Introduction

2. Packaging

1. What is encapsulation?  

2. Features of the package

3. Use of package

3. Inheritance

1. What is inheritance?

2. Characteristics of Inheritance

3. Advantages of inheritance

4. The use of inheritance 

4.1 Inherited format

 4.2 Demonstration of Inheritance

4.3 Member variables

4.4 Member methods

4.5 Construction method

5. Polymorphism

1. What is polymorphism?

2. The characteristics of polymorphism

3. The use of polymorphism 

4. Reference type conversion

 5. Why do you want to transform?

 6. Summary


I. Introduction

         Today, I will summarize the three major characteristics of Java, encapsulation, inheritance, and polymorphism. In fact, the three major features are basic for programmers. After all, as long as you get in touch with Java, you need to know these first, and then I will summarize them systematically.

2. Packaging

1. What is encapsulation?  

        Encapsulation is an important principle of the object-oriented method, which is to combine the properties and operations (or services) of the object into an independent whole, and hide the internal implementation details of the object as much as possible.

  • Some information of the class is hidden inside the class, and external programs are not allowed to make direct access calls.
  • The operation and access to hidden information is realized through the methods provided by this class.
  • Hide object information.
  • Set aside the external interface for access.

​ Take a more popular example, such as our USB interface. If we need peripherals and only need to connect the device to the USB interface, how it works internally is not important to the user. The USB interface is the access interface provided externally.

2. Features of the package

  • Implement more precise control over member variables.
  • Encapsulation can hide the details of internal program implementation.
  • Good encapsulation can reduce the coupling between codes.
  • External members cannot modify the packaged program code.
  • It facilitates data inspection, helps to protect the integrity of object information, and also improves program security.
  • It is easy to modify and improves the maintainability of the code.

3. Use of package

        Use the private keyword to modify member variables. Provide a pair of getXxx methods and setXxx methods corresponding to the member variables that need to be accessed. private is a permission modifier, which represents the minimum permission. It can modify member variables and member methods. The member variables and member methods modified by private can only be accessed in this class. Code example:


public class Student {
  private String name;
  private int age;
 public void setName(String name) {
    this.name = name;
  } 
 public String getName() {
    return name;
  }
 public void setAge(int age) {
    this.age = age;
  } 
 public int getAge() {
    return age;
  }
}

Analysis: For the above entity object, I think everyone is already familiar with it. The member variables in the object are privatized and cannot be accessed by external programs. But we provide external access methods, which are the set and get methods. For such an entity object, the external program only has the authority to assign and obtain values, and cannot modify the internal ones. Therefore, we can also make some logical judgments internally to meet our business needs.

3. Inheritance

1. What is inheritance?

Inheritance means that the subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance fields and methods of the parent class, or the subclass inherits the method from the parent class, so that the subclass has the same behavior as the parent class. Of course, if you have a private attribute (private modification) in the parent class, the subclass cannot be inherited.

2. Characteristics of Inheritance

2.1 Only single inheritance is supported, and a subclass is only allowed to have one parent class

2.2 Subclasses can have the properties and methods of the parent class

2.3 Subclasses can have their own properties and methods

2.4 Subclasses can override parent class methods

2.5 You can declare parent classes and create subclasses (also known as parent class loading subclasses)

      For example: Person p = new Teacher();

                (1) Whatever type is declared, only the type of properties and methods can be called

                (2) What kind of type is created, what type of method is actually run

                 Tips: (1) and (2) are called upward transformation, for example: Person p=new Teacher(); then p can only call methods and properties in the Person class, but actually runs the rewritten method in Teacher , cannot call the private method in Teacher

                (3) Whatever type is created, it can be forced to what type

                 Tip: For example: Person p=new Teacher();

                                       Teacher t=(Teacher) p;

                 This is called downward transformation. At this time, t calls the corresponding properties and methods of the created Teacher type.

3. Advantages of inheritance

  • Improve code reusability
  • The properties and methods of the parent class can be used in the subclass
  • Subclasses can be easily defined
  • Makes designing applications easy

4. The use of inheritance 

4.1 Inherited format

class 父类 {
  ...
} 
 
class 子类 extends 父类 {
...
}

 4.2 Demonstration of Inheritance

/
* *
 定义员工类Employee,做为父类
*/
 
class Employee {
    String name; // 定义name属性
   // 定义员工的工作方法
   public void work() {
 System.out.println("尽心尽力地工作");
}
} 
 
/
* *
定义讲师类Teacher 继承 员工类Employee
*/
class Teacher extends Employee {
// 定义一个打印name的方法
public void printName() {
System.out.println("name=" + name);
  }
}
 
 /
* *
定义测试类
*/
 
public class ExtendDemo01 {
public static void main(String[] args) {
// 创建一个讲师类对象
Teacher t = new Teacher();
// 为该员工类的name属性进行赋值
t.name = "小明";
// 调用该员工的printName()方法
t.printName(); // name = 小明
// 调用Teacher类继承来的work()方法
t.work(); // 尽心尽力地工作
 }
}

4.3 Member variables

        When the member variables do not have the same name, the access to the code has no effect, but when the member variables have the same name, there will be problems with access at this time, for example:


class Fu {
// Fu中的成员变量。
int num = 5;
} 
 
class Zi extends Fu {
// Zi中的成员变量
int num = 6;
public void show() {
// 访问父类中的num
System.out.println("Fu num=" + num);
// 访问子类中的num
System.out.println("Zi num=" + num);
}
} 
 
class ExtendsDemo03 {
public static void main(String[] args) {
// 创建子类对象
Zi z = new Zi();
// 调用子类中的show方法
z.show();
}
} 
 
演示结果:
Fu num = 6
Zi num = 6

        When a member variable with the same name appears in the child parent class, when accessing the non-private member variable in the parent class in the child class, you need to use the super keyword to modify the member variable of the parent class, similar to this. For example:

class Zi extends Fu {
// Zi中的成员变量
int num = 6;
public void show() {
//访问父类中的num
System.out.println("Fu num=" + super.num);
//访问子类中的num
System.out.println("Zi num=" + this.num);
}
} 
 
演示结果:
Fu num = 5
Zi num = 6

4.4 Member methods

        When member methods have the same name, we need to use method override (Override).

        Method rewriting: When the same method as the parent class appears in the subclass (the return value type, method name and parameter list are all the same), there will be an overwriting effect, also known as rewriting or duplication. Declare unchanged, reimplement.

class Phone {
public void sendMessage(){
System.out.println("发短信");
} 
 
public void call(){
System.out.println("打电话");
}
 
public void showNum(){
System.out.println("来电显示号码");
 }
}
//智能手机类
class NewPhone extends Phone {
//重写父类的来电显示号码功能,并增加自己的显示姓名和图片功能
public void showNum(){
//调用父类已经存在的功能使用super
super.showNum();
//增加自己特有显示姓名和图片功能
System.out.println("显示来电姓名");
System.out.println("显示头像");
}
} 
public class ExtendsDemo06 {
public static void main(String[] args) {
// 创建子类对象
NewPhone np = new NewPhone();
// 调用父类继承而来的方法
np.call();
// 调用子类重写的方法
np.showNum();
}
}

Note: When rewriting here, the super. parent class member method is used, which means calling the method of the parent class member.

4.5 Construction method

        First of all, we have to recall two things, the definition format and function of the constructor.
        1. The name of the constructor is consistent with the class name. So subclasses cannot inherit parent class constructors.
        2. The role of the constructor is to initialize member variables. Therefore, in the initialization process of the subclass, the initialization action of the parent class must be executed first. There is a super() in the construction method of the subclass by default, which means calling the construction method of the parent class. After the member variables of the parent class are initialized, they can be used by the subclass.

class Fu {
 private int n;
 Fu(){
  System.out.println("Fu()");
  }
}
 
class Zi extends Fu {
  Zi(){
 // super(),调用父类构造方法
  super();
  System.out.println("Zi()");
  }
} 
public class ExtendsDemo07{
  public static void main (String args[]){
  Zi zi = new Zi();
  }
}
 
输出结果:
Fu()
Zi()

5. Polymorphism

1. What is polymorphism?

        Polymorphism is the ability to have multiple different manifestations or morphologies of the same behavior.

2. The characteristics of polymorphism

  1. Eliminate the coupling relationship between types and achieve low coupling
  2. flexibility
  3. scalability
  4. replaceability

3. The use of polymorphism 

The format of the polymorphic embodiment:

Parent class type variable name = new subclass object;
variable name. method name();

When calling a method in a polymorphic way, first check whether the method exists in the parent class, if not, a compilation error occurs; if so, the subclass overridden method is executed.

Define the parent class:

public abstract class Animal {
    public abstract void eat();
}

Define a subclass:

class Cat extends Animal {
    public void eat() {
        System.out.println("吃鱼");
    }
} 
 
class Dog extends Animal {
    public void eat() {
        System.out.println("吃骨头");
    }
}

Define the test class:


public class Test {
    public static void main(String[] args) {
        // 多态形式,创建对象
        Cat c = new Cat();
        Dog d = new Dog();
        // 调用showCatEat
        showCatEat(c);
        // 调用showDogEat
        showDogEat(d);
        /*
        以上两个方法, 均可以被showAnimalEat(Animal a)方法所替代
        而执行效果一致
        */
        showAnimalEat(c);
        showAnimalEat(d);
    }
    public static void showCatEat (Cat c){
        c.eat();
    } 
    public static void showDogEat (Dog d){
        d.eat();
    } 
    public static void showAnimalEat (Animal a){
        a.eat();
    }
}

        Due to the support of polymorphic features, the Animal type of the showAnimalEat method is the parent class type of Cat and Dog, and the parent class type receives subclass objects. Of course, Cat objects and Dog objects can be passed to the method.
        When the eat method is executed, polymorphism stipulates that the method rewritten by the subclass is executed, and the effect is naturally consistent with the showCatEat and showDogEat methods, so showAnimalEat can completely replace the above two methods.
        Not just a replacement, but in terms of scalability, no matter how many subclasses appear in the future, we don't need to write the showXxxEat method, and we can use showAnimalEat directly.
        Therefore, the benefits of polymorphism are reflected in the fact that it can make programming easier and have good extensions.

4. Reference type conversion

Polymorphic transformation is divided into two types: upward transformation and downward transformation:
Upward transformation: polymorphism itself is the process of upward transformation from subclass type to parent class type, and this process is the default. Upcasting occurs when a parent class reference points to a subclass object.
use format

Parent class type variable name = new subclass type ();
such as: Animal a = new Cat ();

Downcasting: The process of downcasting from the parent class type to the subclass type, this process is mandatory.
For a subclass object that has been upwardly transformed, the parent class reference can be converted into a subclass reference, and the forced type conversion format can be used, which is downcasting.
Use the format:

Subclass type variable name = (subclass type) parent class variable name;
such as: Cat c = (Cat) a;

 5. Why do you want to transform?

When calling a method in a polymorphic way, first check whether the method exists in the parent class, if not, a compilation error occurs. That is to say, you cannot call methods owned by subclasses but not in superclasses. Compilation is wrong, let alone run. This is also a little "little trouble" that polymorphism brings us. Therefore, if you want to call a subclass-specific method, you must do downcasting.

Define class:

abstract class Animal {
    abstract void eat();
} 
 
class Cat extends Animal {
    public void eat() {
        System.out.println("吃鱼"); 
    } 
    public void catchMouse() {
        System.out.println("抓老鼠");
    }
} 
class Dog extends Animal {
    public void eat() {
        System.out.println("吃骨头");
    }
    public void watchHouse() {
        System.out.println("看家");
    }
}

Define the test class:


public class Test {
    public static void main(String[] args) {
        // 向上转型
        Animal a = new Cat();
        a.eat(); // 调用的是 Cat 的 eat
        // 向下转型
        Cat c = (Cat)a;
        c.catchMouse(); // 调用的是 Cat 的 catchMouse
    }
}

Note: When converting here, sometimes conversion exceptions may occur, for example:

public class Test {
    public static void main(String[] args) {
        // 向上转型
        Animal a = new Cat();
        a.eat(); // 调用的是 Cat 的 eat
        // 向下转型
        Dog d = (Dog)a;
        d.watchHouse(); // 调用的是 Dog 的 watchHouse 【运行报错】
    }
}

        This is because, obviously creating a Cat type object, of course it cannot be converted into a Dog object at runtime. These two types do not have any inheritance relationship and do not meet the definition of type conversion. In order to avoid the occurrence of ClassCastException, Java provides the instanceof keyword to check the type of the reference variable. The format is as follows:

VariableName instanceof DataType
Returns true if the variable is of this datatype.
Returns false if the variable does not belong to the data type.

So we can make a judgment before the conversion

public class Test {
    public static void main(String[] args) {
        // 向上转型
        Animal a = new Cat();
        a.eat(); // 调用的是 Cat 的 eat
        // 向下转型
        if (a instanceof Cat){
            Cat c = (Cat)a;
            c.catchMouse(); // 调用的是 Cat 的 catchMouse
        } else if (a instanceof Dog){
            Dog d = (Dog)a;
            d.watchHouse(); // 调用的是 Dog 的 watchHouse
        }
    }
}

 6. Summary

        The above are the knowledge points about java encapsulation, inheritance, and polymorphism collected by the editor. If you have any questions, please comment and exchange. I look forward to becoming stronger with you! ! !

 

Guess you like

Origin blog.csdn.net/wct040923/article/details/130528785