Three object-oriented features of Java and abstract classes and interfaces


Three object-oriented features

Object oriented has three characteristics: encapsulation, inheritance and polymorphism.

encapsulation

Encapsulation, which is also one of the characteristics of object-oriented thought.

Packaging overview

Packaging performance:

  • Method is a basic package.
  • Class is also a wrapper.

From the above two points, it can be concluded that the benefits of packaging are:

  • It improves the reusability of the code.
  • It hides the implementation details and provides external access. It is convenient for the caller to use. This is one of the core, which can also be understood as the concept of encapsulation.
  • Improved security.

For example, a computer consists of CPU, motherboard, graphics card, memory, hard disk, power supply and other components. In fact, we can use the computer by assembling these components together. However, we find that these components are scattered outside, which can cause unsafe factors. Therefore, we use the chassis shell to install these components inside, and leave some sockets on the chassis shell, If you don't leave a socket, let's think about what will happen. Conclusion: the chassis actually hides the details of card handling equipment, and provides external access to internal details such as sockets and switches.

inherit

Concept of inheritance

In real life, inheritance generally means that children inherit the property of their parents. In the program, inheritance describes the ownership relationship between things. Through inheritance, a relationship system can be formed between a variety of things.

For example, the employees of the R & D department and the maintenance department in the company belong to employees. In the program, it can be described that the employees of the R & D department and the maintenance department inherit from the employees. Similarly, Java EE engineers and Android engineers inherit from the employees of the R & D department, while dimension network maintenance engineers and hardware maintenance engineers inherit from the employees of the maintenance department. An inheritance system will be formed among these employees, as shown in the figure below.

In Java, class inheritance refers to the construction of a new class on the basis of an existing class. The constructed new class is called a subclass, and the existing class is called a parent class. The child class will automatically own all inheritable properties and methods of the parent class.

Inherited formats & use

In the program, if you want to declare that one class inherits another class, you need to use the extends keyword. Format: class subclass extends parent class {} next, learn how the subclass inherits the parent class through a case, as shown below. Employee .java

/*
* Define Employee class
*/
public class Employee {
    String name; // Define the name attribute
    // Define employee's working methods
    public void work() {
        System.out.println("Work hard");
    }
}
/*
* Define the R & D department employee class. Developer inherits the Employee class employee
*/
class Developer extends Employee {
    // Define a method to print name
    public void printName() {
        System.out.println("name=" + name);
    }
}
* Define test class
*/
public class Example01 {
    public static void main(String[] args) {
        Developer d = new Developer(); // Create an R & D Employee class object
        d.name = "Xiao Ming"; // Assign a value to the name attribute of the Employee class
        d.printName(); // Call the printName() method of the employee
        d.work(); // Call the work() method inherited from the Developer class
    }
}

The operation results are shown in the figure below.

In the above code, the Developer class inherits the Employee class through the extends keyword, so the Developer class is a subclass of the Employee class. It is not difficult to see from the running results that although the subclass does not define the name attribute and work() method, it can access these two members. This means that when a subclass inherits from the parent class, it will automatically have the members of the parent class.

Benefits & considerations of inheritance

Benefits of inheritance:

  • The emergence of inheritance improves the reusability of code and improves the efficiency of software development.
  • The emergence of inheritance makes the relationship between classes and provides the premise of polymorphism.

In class inheritance, we need to pay attention to some problems, as follows: 1. In Java, classes only support single inheritance and multiple inheritance is not allowed, that is, a class can only have one direct parent class. For example, the following situation is illegal.

class A{} 
class B{}
class C extends A,B{} // Class C cannot inherit class A and class B at the same time

2. Multiple classes can inherit a parent class. For example, the following is allowed.

class A{}
class B extends A{}
class C extends A{} // Both class B and class C can inherit class A

3. In Java, multi-layer inheritance is possible, that is, the parent class of a class can inherit another parent class. For example, class C inherits from class B, and class B can inherit class A. at this time, class C can also be called a subclass of class A. The following situations are allowed.

class A{}
class B extends A{} // Class B inherits class A, and class B is a subclass of class A
class C extends B{} // Class C inherits class B. class C is a subclass of class B and a subclass of class A

4. In Java, subclass and parent class are relative concepts, that is, a class can be a parent class of a class and a subclass of another class at the same time. For example, in the above case, class B is a subclass of class A and a parent of class C.

Inheritance - Characteristics of member variables in child parent classes

Understand the benefits of inheritance and improve the reusability of code. Inheritance creates a relationship between classes or objects. So, when inheritance appears, what changes have taken place among the members of the class? Member variable: if a member variable with a different name appears in the parent class of a child class, there is no problem accessing it. See the following code:

class Fu
{
    //Member variables in Fu.
    int num = 5;
}
class Zi extends Fu
{
    //Member variables in Zi
    int num2 = 6;
    //Member method in Zi
    public void show()
    {
//Access num in parent class
        System.out.println("Fu num="+num);
//Access num2 in subclasses
        System.out.println("Zi num2="+num2);
    }
}
class Demo
{
    public static void main(String[] args)
    {
        Zi z = new Zi(); //Create subclass objects
        z.show(); //Call the show method in the subclass
    }
}

Code Description: the member variables in Fu class are non private and can be accessed directly in subclasses. If the member variables in Fu class are private, subclasses cannot be accessed directly.

When a member variable with the same name appears in the child parent class, the keyword super must be used to access the member variable in the parent class in the child class. Super is used to represent the reference of the parent object space contained in the current object. In the subclass, access the member variable format in the parent class: super. See the following code for the member variable in the parent class:

class Fu
{
    //Member variables in Fu.
    int num = 5;
}
class Zi extends Fu
{
    //Member variables in Zi
    int num = 6;
    void show()
    {
//When a member variable with the same name appears in the child parent class
//When you need to access non private member variables in the parent class in a subclass, you need to use the super keyword
//Access num in parent class
        System.out.println("Fu num="+super.num);
//Access num2 in subclasses
        System.out.println("Zi num2="+this.num);
    }
}
class Demo5
{
    public static void main(String[] args)
    {
        Zi z = new Zi(); //Create subclass objects
        z.show(); //Call the show method in the subclass
    }
}

Inheritance - Characteristics of member methods in child and parent classes - override & Application

Characteristics of member methods in child and parent classes when calling methods through objects in the program, you will first find out whether there are corresponding methods in the child class. If there are methods in the child class, the methods in the child class will be executed. If there are no methods in the child class, the corresponding methods in the parent class will be executed. See the following code:

class Fu{
    public void show(){
        System.out.println("Fu Class show Method execution");
    }
}
class Zi extends Fu{
    public void show2(){
        System.out.println("Zi Class show2 Method execution");
    }
}
public class Test{
    public static void main(String[] args) {
        Zi z = new Zi();
        z.show(); //There is no show method in the subclass, but the parent method can be found to execute
        z.show2();
    }
}

Member method special case - override

A subclass as like as two peas is exposed, which will result in overlay operations, also known as override rewriting, copying, or overwriting.

class Fu
{
    public void show()
    {
        System.out.println("Fu show");
    }
}
class Zi extends Fu
{
    //The subclass duplicates the show method of the parent class
    public void show()
    {
        System.out.println("Zi show");
    }
}

Application of method rewrite (override)

When a subclass needs the function of the parent class and the subclass of the function subject has its own unique content, you can override the methods in the parent class. In this way, you not only follow the function of the parent class, but also define the unique content of the subclass. For example, when describing a mobile phone, it has the functions of sending text messages, making calls and displaying incoming call numbers. Later, because the mobile phone needs to add the display name and avatar in the incoming call display function, you can redefine a class to describe the smart phone and inherit the original class describing the mobile phone. And override the caller ID function in the newly defined class, and add the function of displaying name and avatar. In the subclass, access the member method in the parent class. Format: super. Member method in the parent class (); See the following code:

//Mobile phone class
class Phone{
    public void sendMessage(){
        System.out.println("send message");
    }
    public void call(){
        System.out.println("phone");
    }
    public void showNum(){
        System.out.println("Caller ID number");
    }
}

//Smart phones
class NewPhone extends Phone{

    //Override the caller ID function of the parent class, and add its own display name and picture function
    public void showNum(){
//Call the function whose parent class already exists and use super
        super.showNum();
//Add your own unique function of displaying names and pictures
        System.out.println("Show caller name");
        System.out.println("Show Faces ");
    }
}

Method override considerations

Details of Rewriting: when a subclass method overrides a parent method, you must ensure that the permission is greater than or equal to the permission of the parent.

class Fu(){
    void show(){}
    public void method(){}
}
class Zi() extends Fu{
    public void show(){} //There is no problem compiling and running
        void method(){} //Compilation error
}

Note a little as like as two peas: the method returns the value type, the method name parameter list is the same.

Summary: when a class is one of another class, you can inherit properties and functions through inheritance. If the function content of the parent class needs special definition of the child class, override the method.

You cannot inherit a function at will. You must comply with the relationship between is a nd a

  • Apple is a fruit
  • Man is a man
  • Dog is a man, this situation can not be inherited

Comparison between overloading and rewriting

heavy load

Permission modifier (public private default): irrelevant method name: the method names of two overloaded methods must be the same. Formal parameter list:

  • The order of parameter types is different
  • The number of formal parameters is different
  • Different types of formal parameters

The three satisfy at least one return value type: overloading is independent of the return value type

rewrite

Permission modifier (public private default): permission of subclass method > = permission of parent method method method name: subclass method and parent method must be the same formal parameter list: formal parameter list of subclass method and parent method must be the same return value type: basic class data type: must be the same reference data type: return value type of subclass method and return value type of parent method are the same, Or the return value type of the subclass method is a subclass of the return value type of the parent method

abstract class

Abstract class - generation

When writing a class, we often define some methods for the class. These methods are used to describe the specific implementation of the function of the class. Then these methods have specific method bodies. But sometimes, a parent class only knows what methods should be included in the subclass, but it can't know exactly how the subclass implements these methods.

For example, a graphic class should have a method for calculating the perimeter, but the algorithm for calculating the perimeter is different for different graphics. What should I do? When analyzing things and finding common content, upward extraction occurs. There is a special case where the method function declarations are the same, but the method function bodies are different. There are still some, some functions (work) are not specific.

These non-specific functions need to be identified in the class through the keyword abstract in java. When an abstract function is defined, the class must also be modified by the abstract keyword. The class modified by the abstract keyword is an abstract class.

Abstract class & definition of abstract method

Format of abstract method definition:

public abstract Return value type method name(parameter);
    Format of abstract class definition:
    abstract class Class name {
}

See the following code:

//R & D staff 
abstract class Developer {
    public abstract void work();//abstract functions. Need abstract modification and semicolon; end
}

//Java EE Engineer
class JavaEE extends Developer{
    public void work() {
        System.out.println("Taobao website is being developed");
    }
}
//Android Engineer

class Android extends Developer {
    public void work() {
        System.out.println("Taobao mobile client software is being developed");
    }
}

Characteristics of abstract classes

  • 1. Abstract classes and abstract methods need to be modified by abstract. Abstract methods must be defined in abstract classes.
  • 2. Abstract classes cannot create objects directly. Reason: it is meaningless to call abstract methods.
  • 3. Only when all abstract methods in an abstract class are overridden can its subclasses create objects. Otherwise, the subclass is still an abstract class.

The reason why we inherit abstract classes is more in the thought that it will be easier to operate in the face of common types.

Details of abstract class: 1. Must an abstract class be a parent class? Yes, because it's constantly drawn. 2. Whether abstract methods can not be defined in abstract classes. Yes, what is the significance of the existence of this abstract class? Instead of letting this class create objects, the method can directly let subclasses use it. 3. What keywords can't abstract coexist with?

  • Private: private method subclasses cannot be inherited, and there is no coverage. abstract and private use modifier methods together. abstract requires subclasses to implement this method, while private modifier subclasses cannot get the parent method at all. Contradictory.

Package access modifier

Declaration format of package

The company website is usually used for reverse writing. There can be multi-layer packages. The package name adopts all lowercase letters, and the multi-layer packages are connected with ".".
Declaration format of package in class: package package name. Package name. Package name;

Package access

Package access when accessing a class, in order to find the class, you must use the full name of the class containing the package name (package name. Class name). Package name. Package name... Class name, such as: java.util.Scanner class with package, creation object format: package name. Class name variable name = new package name. Class name (); Premise: package access is closely related to access permission. Generally speaking, the class is decorated with public.

Simplified access to class when we want to use a class, the class is in the same package (i.e. the same folder) as the current program, or the class is a class in java.lang package, we can usually omit the package name and use the class directly. When the class we want to use is not in the same package (i.e. in a different folder) as the current program, the class to be accessed must be modified with public.

import package

Every time we use a class, we need to write a long package name. It's very troublesome. We can simplify it by importing packages. By using this class in the way of package guide, you can avoid writing with the full class name (that is, package class. Class name). Import package format: import package name. Class name;

When the program imports the specified package and uses the class, it can be simplified. Where to write the import package code: after declaring the package and before defining all class classes, use the import package import package name. Package name. Class name;

The access permissions of data members and member functions in the class include: public, private, protect and default (package access permissions)

public

Publicity; Can be accessed by all other classes.

private

  • This kind of access is private; Can only be accessed and modified by yourself.

protected

Children and friends can access and protect; Itself, subclasses and classes in the same package can be accessed.

friendly(default)

Almost no default: classes in the same package can be accessed. They are declared as friendly without modifiers.

Summary:

  • To be accessible only in this class, use the private modifier;
  • All classes in this package can be accessed without modifiers;
  • To access classes in this package and subclasses in other packages, use the protected modifier
  • To make all classes in all packages accessible, use the public modifier.
  • Note: if the class is decorated with public, the class name must be the same as the file name. There can only be one public modified class in a file.

Interface

Interface concept

An interface is a collection of functions. It can also be regarded as a data type. It is a "class" more abstract than an abstract class. The interface only describes the methods it should have, and there is no specific implementation. The specific implementation is completed by the implementation class of the interface (equivalent to the subclass of the interface). In this way, the definition and implementation of functions are separated, and the program design is optimized. Remember: everything has a function, that is, everything has an interface.

Definition of interface

Different from defining the class of a class, the interface keyword needs to be used when defining an interface. The interface is still defined in a. java file. Although the interface keyword used in the declaration will still produce a. Class file after compilation. This allows us to think of an interface as a special class that contains only functional declarations. Define format:

public interface Interface name {
    Abstract method 1;
    Abstract method 2;
    Abstract method 3;
}

interface is used instead of the original class. Other steps are the same as defining the class:

  • The methods in the interface are abstract methods for public access
  • Ordinary member variables cannot be defined in an interface

Class implementation interface

The relationship between class and interface is implementation relationship, that is, class implements interface. The implemented actions are similar to inheritance, but the keywords are different. The implementation uses implements. After other classes (implementation classes) implement the interface, they are equivalent to declaring: "I should have the functions in this interface". Implementation classes still need to override methods to implement specific functions. Format:

class class implements Interface {
    Override methods in interfaces
} 

After the class implements the interface, the class will inherit the abstract method in the interface. At this time, the class needs to rewrite the abstract method to complete the specific logic.

The function is defined in the interface. When the function is required, the class can implement the interface. It only declares that the method should be provided, which is the declaration of the function. Rewriting a method in a specific implementation class to implement a function is the specific implementation of a method. Therefore, the declaration and implementation of functions are separated through the above two actions.

Characteristics of members in the interface

  • Variables can be defined in the interface, but variables must be decorated with fixed modifiers, public static final. Therefore, variables in the interface are also called constants, and their values cannot be changed. We will explain the static and final keywords later
  • Methods can be defined in the interface
  • Interface cannot create object
  • A subclass can be instantiated only after it overrides all the methods in the interface. Otherwise, the subclass is an abstract class.
class DemoImpl implements Demo { //Subclasses implement the Demo interface.
    //Override methods in the interface.
    public void show1(){}
    public void show2(){}
}

Multiple implementation of interface

After understanding the characteristics of the interface, think about why to define the interface and use abstract class description. What is the use of the interface? The most important embodiment of interface: solve the disadvantages of multi inheritance. The multi inheritance mechanism is implemented in java.

interface Fu1
{
    void show1();
}
interface Fu2
{
    void show2();
}
class Zi implements Fu1,Fu2// Multiple implementations. Implement multiple interfaces at the same time.
{
    public void show1(){}
    public void show2(){}
}

How to solve the disadvantages of multi inheritance?

Disadvantages: in case of multiple inheritance, when multiple parent classes have the same function, the subclass call will produce uncertainty. In fact, the core reason is that the function in the multi inheritance parent class has a subject, which leads to the uncertainty of which subject content to run when calling the runtime. Why can multiple implementations be solved? Because the functions in the interface have no method body, they are defined by subclasses.

Class inherits classes and implements interfaces at the same time

The relationship between interfaces and classes can be generated through implementation, and the relationship between classes can be generated through inheritance. When a class has inherited a parent class and it needs to extend additional functions, the interface comes in handy. Subclasses extend functions by inheriting the parent class. The functions extended by inheritance are the basic functions that subclasses should have. What if the subclass wants to continue to extend the functionality in other classes? This is done by implementing the interface.

class Fu {
    public void show(){}
}
interface Inter {
    pulbic abstract void show1();
}
class Zi extends Fu implements Inter {
    public void show1() {
    }
}

The appearance of interface avoids the limitation of single inheritance. The basic functions of things defined in the parent class. Extension function of things defined in the interface.

Multiple inheritance of interfaces

Extensions can be used for inheritance between multiple interfaces.

interface Fu1{
    void show();
}
interface Fu2{
    void show1();
}
interface Fu3{
    void show2();
}
interface Zi extends Fu1,Fu2,Fu3{
    void show3();
}

In development, if the same methods exist in multiple interfaces, if a class implements these interfaces, the methods in the interface must be implemented. Because the methods in the interface are abstract methods, there will be no call uncertainty after subclass implementation.

Interface idea

I learned the code embodiment of the interface. Now let's learn the idea of the interface. Next, I'll explain it from examples in life. For example: we all know that there are many sockets on the computer, and these sockets can be inserted into the corresponding devices. Why can these devices be inserted on it? The main reason is that these devices comply with the use rules of this socket during production, otherwise they will not be able to be inserted into the interface, let alone used. The discovery of this socket allows us to use more devices. Summary: benefits of interfaces in development

  • 1. The appearance of the interface extends the function.
  • 2. An interface is actually a rule that leaks out.
  • 3. The appearance of interface reduces the coupling, that is, the decoupling between devices is realized.

The appearance of the interface is convenient for later use and maintenance. One party is using the interface (such as computer) and the other party is implementing the interface (equipment plugged into the socket). For example, notebooks use this rule (Interface), and computer peripherals implement this rule (Interface).

The difference between interface and abstraction

Dogs are divided into many kinds. Their way of roaring and eating is different. They can't be specific when describing, that is, the behavior of roaring and eating can't be clear. When describing a behavior, the specific action of the behavior cannot be defined. In this case, the behavior can be written as an abstract behavior, and this class is also an abstract class.

But when the anti drug dog has other additional functions, this function is not in the system of this thing. At this time, the anti drug dog can not only have the characteristics of canine, but also have other additional functions. This additional function can be defined in the interface. The following code demonstrates:

interface Anti drug{
    public abstract void Anti drug();
}
//Define the common functions of this reminder in Canidae
abstract class Canidae{
    public abstract void having dinner();
    public abstract void Roar();
}
// Anti drug dogs belong to the canine family. Let them inherit the characteristics of the canine family,

//Since the anti drug dog has the anti drug function, it only needs to realize the anti drug interface, which ensures that the anti drug dog has the characteristics of canine and the anti drug function
class Sniffer Dog extends Canidae implements Anti drug{

    public void Anti drug() {
    }
    void having dinner() {
    }
    void Roar() {
    }
}
class Anti drug pig implements Anti drug{
    public void Anti drug() {
    }
}

Summarize the differences between interfaces and abstract classes through the above examples:

Similarities:

  • Are at the top of inheritance and used to be implemented or inherited by other classes;
  • Cannot instantiate objects directly;
  • Both contain abstract methods, and their subclasses must override these abstract methods;

difference:

  • Abstract classes provide implementations for some methods to avoid subclasses implementing these methods repeatedly and improve code reusability; Interfaces can only contain abstract methods;
  • A class can only inherit one direct parent class (possibly an abstract class), but can implement multiple interfaces; (the interface makes up for the single inheritance of Java)
  • Abstract class is the content of this thing, and the inheritance system is an is... a relationship
  • The interface is the extra content in this thing, and the inheritance system is a like... A relationship

Selection of the two: give priority to the interface and minimize the use of abstract classes; Abstract classes are selected when it is necessary to define the behavior of subclasses and provide common functions for subclasses;

polymorphic

Polymorphism is the third feature of object-oriented after encapsulation and inheritance. Real things often reflect a variety of forms, such as students. Students are a kind of people, so a specific classmate Zhang San is both a Student and a Person, that is, there are two forms. As an object-oriented language, Java can also describe many forms of a thing. If the Student class inherits the Person class, the object of a Student is both Student and Person. The polymorphic code in Java is reflected in that a subclass object (implementation class object) can not only assign values to the reference variables of this subclass (implementation class object), but also assign values to the parent class (Interface) variables of this subclass (implementation class object). For example, the Student class can be a subclass of the Person class. Then a Student object can be assigned to either a Student type reference or a Person type reference.

  • Finally, the polymorphism is reflected in that the parent class reference variable can point to the child class object.
  • The premise of polymorphism is that there must be child parent class relationship or class implementation interface relationship, otherwise polymorphism cannot be completed.
  • When a method is called with a polymorphic parent class reference variable, the overridden method of the child class will be called.

Definition and usage format of polymorphism

Polymorphic definition format: refers to the reference variable of the parent class pointing to the subclass object

Parent type variable name = new Subclass type();
Variable name.Method name();

Format of common class polymorphism definition

Parent variable name = new Subclass();
For example:    class Fu {}
class Zi extends Fu {}
//Polymorphic use of classes
Fu f = new Zi();

Format of abstract class polymorphism definition

Abstract class variable name = new abstract class subclass (); For example:

abstract class Fu {
    public abstract void method();
}
class Zi extends Fu {
    public void method(){
        System.out.println("Override parent class abstract method");
    }
}
//Polymorphic use of classes
Fu fu= new Zi();

Format of interface polymorphism definition

Interface variable name = new interface implementation class (); For example:

interface Fu {
    public abstract void method();
}
class Zi implements Fu {
    public void method(){
        System.out.println("Override interface abstract method");
    }
}
//Polymorphic use of interfaces
Fu fu = new Zi();

matters needing attention

The methods of the same parent class will be overridden by different subclasses. When calling a method, the method called is the overridden method of each subclass.

Person p1 = new Student();
Person p2 = new Teacher();
p1.work(); //p1 will call the overridden work method in the Student class
p2.work(); //p2 will call the overridden work method in the Teacher class

When the variable name points to different subclass objects, different methods will be called because each subclass overrides the contents of the parent method.

Polymorphism - Characteristics of members

Polymorphism will lead to weak changes in member variables in child and parent classes. See the following code

class Fu {
    int num = 4;
}
class Zi extends Fu {
    int num = 5;
}
class Demo {
    public static void main(String[] args) {
        Fu f = new Zi();
        System.out.println(f.num);//4
        Zi z = new Zi();
        System.out.println(z.num);//5
    }
}

Polymorphic member variable

When a member variable with the same name appears in the child parent class, when calling the variable: compilation time: refers to whether there is a called member variable in the class to which the reference variable belongs. No, compilation failed. Run time: it is also a member variable in the class to which the reference variable belongs. Simple note: both compilation and operation refer to the left side of the equal sign. Compile and run. Look at the left.

Polymorphism will lead to slight changes in member methods in child and parent classes. See the following code

class Fu {
    int num = 4;
    void show()    {
        System.out.println("Fu show num");
    }
}
class Zi extends Fu {
    int num = 5;
    void show()    {
        System.out.println("Zi show num");
    }
}
class Demo {
    public static void main(String[] args) {
        Fu f = new Zi();
        f.show();
    }
}

Polymorphic member method

Compilation time: refer to the class to which the reference variable belongs. If there is no method called in the class, the compilation fails. Run time: refers to the class of the object to which the reference variable refers, and runs the member methods in the class to which the object belongs. In short: compile to the left and run to the right.

instanceof keyword

We can use the instanceof keyword to determine whether an object belongs to a data type. For example, the object of students belongs to students, and the object of students also belongs to human beings. Use format:

boolean b = object instanceof data type;

as

Person p1 = new Student(); // Prerequisite, the student class has inherited human beings
boolean flag = p1 instanceof Student; //flag result is true
boolean flag2 = p2 instanceof Teacher; //flag result is false

Polymorphism transformation

Polymorphic transformation can be divided into upward transformation and downward Transformation: upward Transformation: when a subclass object is assigned to a parent class reference, it is upward transformation. Polymorphism itself is the process of upward transformation.

Usage format: parent type variable name = new subclass type (); For example: Person p = new Student();

Downward Transformation: a subclass object that has been transformed upward can use the format of forced type conversion to convert the parent class reference into a subclass reference. This process is downward transformation. If you create a parent object directly, you cannot transform down!

Usage format: subclass type variable name = (subclass type) variable of parent type; For example: Student stu = (Student) p// The variable p actually points to the student object

Advantages and disadvantages of polymorphism

When the reference of the parent class points to the subclass object, an upward transformation occurs, that is, the subclass type object is transformed into the parent type. The advantage of upward transformation is to hide the subclass types and improve the scalability of the code. However, the upward transformation also has disadvantages. Only the common contents of the parent class can be used, but the unique functions of the child class cannot be used, and the functions are limited. See the following code

//Describe animals and extract common eat methods
abstract class Animal {
    abstract void eat();
}

// Describe the dog class, inherit the animal class, rewrite the eat method and add the lookHome method
class Dog extends Animal {
    void eat() {
        System.out.println("Gnaw a bone");
    }

    void lookHome() {
        System.out.println("Housekeeping");
    }
}

// Describe cat class, inherit animal class, rewrite eat method and add catchMouse method
class Cat extends Animal {
    void eat() {
        System.out.println("Eat fish");
    }

    void catchMouse() {
        System.out.println("Catch a mouse");
    }
}

public class Test {
    public static void main(String[] args) {
        Animal a = new Dog(); //Polymorphic form to create a dog object
        a.eat(); // Calling the method in the object will execute the eat method in the dog class
// a.lookHome();// Using the methods unique to Dog class requires downward transformation and cannot be used directly

// In order to use the dog's lookHome method, it needs to be transformed downward
// In the process of downward transformation, type conversion errors may occur, that is, ClassCastException exceptions
// Then, you need to make a robustness judgment before turning 
        if( !a instanceof Dog){ // Judge whether the current object is of Dog type
            System.out.println("Type mismatch, cannot convert");
            return;
        }
        Dog d = (Dog) a; //Downward transformation
        d.lookHome();//Call the dog's lookHome method
    }
}

Let's summarize:

When to use upward Transformation: when you do not need to face subclass types, you can use upward transformation by improving extensibility or using the functions of the parent class.

For example:

Animal a = new Dog();
a.eat();

When to use downward Transformation: when you want to use subclass specific functions, you need to use downward transformation. For example:

Dog d = (Dog) a; //Downward transformation
d.lookHome();//Call the dog's lookHome method

Benefits of downward Transformation: subclass specific functions can be used.

The disadvantages are: you need to face specific subclass objects; ClassCastException type conversion exceptions are easy to occur during downward transformation. Type judgment must be made before conversion. For example: if (! A instanceof dog) {...}

Functions of encapsulation, inheritance and polymorphism:

Encapsulation: hide the implementation details of object attributes and methods, and only provide some public access methods. Inheritance: the subclass will automatically own all inheritable properties and methods of the parent class. Polymorphism: combined with inheritance and method rewriting, it improves the reusability and expansibility of code; Polymorphism is also meaningless without method rewriting. Polymorphic member access features: the operation of methods is on the right, and others are on the left

Class to class, class to interface, interface to interface relationship

Between classes: inheritance relationship, single inheritance. It can be multi-layer inheritance. Between classes and interfaces: implementation relationship, single implementation, or multiple interfaces: inheritance relationship, single inheritance, or multiple inheritance. Classes in Java can inherit a parent class and implement multiple interfaces at the same time

Tags: Java Back-end jdk8

Posted on Sat, 23 Oct 2021 19:22:42 -0400 by fenrir