In-depth understanding of Java object-oriented three characteristics encapsulation inheritance polymorphism

Source: Internet
Author: User
Tags modifier throw exception

1. Encapsulation

Definition of encapsulation:

    • The first is abstraction, abstracting things into a class, followed by encapsulation, hiding the properties and actions of things, preserving only certain methods to communicate with the outside world.

Why encapsulation is required:

    • Encapsulation conforms to the first rule of object-oriented design: The principle of singleness, a class encapsulates what it is doing, rather than exposing it to other classes, and when internal logic changes, external calls do not have to be modified, they only invoke an open interface, instead of caring for the internal implementation

Example:

public class human{    private int age;    private String name;    public int getage ()    {        return age;    }    public void Setage (int age) throws Exception    {        //encapsulates the test logic of age, rather than exposing each caller to handle        if (age >)        {            T Hrow New Exception ("Invalid value of age");        }        This.age = age;    }    Public String getName ()    {        return name;    }    public void SetName (String name)    {        this.name = name;    }}
2. Inheritance

Classes in Java can be categorized into three categories:

    • Class: Using class definition, no abstract method
    • Abstract class: Using the abstract class definition, you can have or without abstract methods
    • Interfaces: Using Inerface definitions, only abstract methods

The following relationships exist between these three types:

    • Classes can be extends: classes, abstract classes (all abstract methods must be implemented), but only one extends, can implements multiple interfaces (all interface methods must be implemented)
    • Abstract classes can be extends: classes, abstract classes (full, partial, or completely non-implementing the parent abstract method), can implements multiple interfaces (all, part, or completely do not implement interface methods)
    • Interface can only extends one interface

What the subclass can get after inheriting:

    • Subclasses have properties and methods that are not private to the parent class
    • Subclasses can add their own methods and properties, that is, to extend the parent class
    • Subclasses can redefine the method of the parent class, that is, the overlay inside the polymorphic, which is detailed later

About constructors:

    • Constructors cannot be inherited, subclasses can call the constructor of a parent class through Super ()
    • When you create a subclass, the compiler automatically calls the parent class's parameterless constructor
    • If the parent class does not have a parameterless constructor defined, the subclass must display the call using Super () in the first line of the constructor's code

The class has an parameterless constructor by default, and if other arguments are defined, the parameterless function fails, so the parent class does not define an parameterless constructor, not the parent class without a write-no-argument constructor. Look at the following example, the parent class is human, and the subclass is programmer.

public class human{    //defines a parameter constructor, the default parameterless constructor fails public    Human (String name)    {    }}
public class Programmer    extends human{public    Programmer ()    {        //If the call is not displayed, the compiler will receive the following error        // Implicit super constructor Human () is undefined. Must explicitly invoke another constructor        super ("X");}    }

Why you need to inherit:

    • Code reuse is a point, the most important is the so-called transformation, that is, the parent class reference variable can point to the subclass object, which is the Java object-oriented most important characteristics of the basis of polymorphism
3. polymorphic

Before you understand polymorphism, you first need to know the unique identity of the method that is what is the same/different method:

    • A method can be composed of: modifier such as public, static+ return value + method name + parameter +throw Exception 5 part
    • Only method names and parameters are unique identifiers, meaning that they are the same way as long as the method name and parameters are the same
    • The so-called parameter is the same, refers to the number of parameters, type, the order of the same, any one of the different methods are different

What is overloading:

    • Overloading refers to a method in which a class (including a method of the parent class) has the same method name, but with different parameters, the parameters can be of varying number, type, or order.
    • If it's just a modifier, a return value, a throw exception, that's 2 of the same method, and the compilation will pass, not to mention overloading the
Example of overloading public class Programmer    extends human{public    void Coding () throws Exception    {    }    Public void Coding (String langtype)    {    } public    String Coding (String Langtype, String project)    {        Retu RN "";    }}
This is not an overload, but three identical methods, compile error public class Programmer    extends human{public    void Coding () throws Exception    {    } public    void coding ()    {    } public    String coding ()    {        return "";    }}

What is overwrite/rewrite:

    • Overrides a behavior that describes a subclass when there is an inheritance relationship
    • A subclass with the same method as the parent class is overwritten, so remember the previous description of the same method, with the same method name and parameter, including the number of arguments, the type, the order
public class human{Public    void Coding (String langtype)    {    }}
public class Programmer    extends human{    //This method overrides/overrides public    void coding (String langtype)    {    }< c24/>//This method is overloaded with the above method public    void Coding (String langtype, String project)    {    }}

overriding/overriding rules:

    • Subclasses cannot overwrite the parent class private method, the private child class is not visible, if the subclass defines a method that is the same as the private method of the parent class, it is a new method
    • The modifier for the overridden method must be greater than the modifier for the overridden method (Public > Protected > Default > Private)
    • The exception thrown by the override needs to be the same as the parent class or the subclass of the parent exception, or the overriding method simply does not write throws
    • The return value of the overridden method must be the same as the overridden method, or the compilation error
    • Static methods cannot be overridden as non-static methods, otherwise compilation error

Understanding the above points of knowledge, it is time to define polymorphism:

    • Polymorphism can be said to be "an interface, multiple implementations" or a reference variable of a parent class can point to an instance of a subclass, the type of the referenced object determines whose method is called, but this method must be defined in the parent class
    • Polymorphism can be divided into two types: compile-time polymorphism (method overloading) and run-time polymorphism (override of the inherited method), compile-time polymorphism is well understood, and the latter is for runtime polymorphism
    • Run-time polymorphism relies on inheritance, rewriting, and upward transformation

above example:

 class human{public void ShowName () {System.out.println ("I am Human"); }}//inheritance Relationship class Doctor extends human{//method overrides public void ShowName () {System.out.println ("I am Doctor")    ;    }}class Programmer extends human{public void ShowName () {System.out.println ("I am Programmer");  }}public class test{//Up Transformation public Human humanfactory (String humantype) {if ("Doctor". Equals (Humantype        ) {return new Doctor ();        } if ("Programmer". Equals (Humantype)) {return new programmer ();    } return new Human ();        } public static void Main (String args[]) {test test = new test ();        Human Human = Test.humanfactory ("Doctor");        Human.showname ();//output:i am Doctor human = test.humanfactory ("programmer"); Human.showname ();//output:i am Programmer//An interface method, showing a different form, meaning that is polymorphic also}} 

The drawback of upward transformation:

    • Only properties and methods defined in the parent class can be called, and for methods and properties in subclasses it is not a good choice, it must be strongly turned into a subclass type

Summary:

    • When a Superclass object reference variable refers to a subclass object, the type of the referenced object rather than the type of the reference variable determines which member method to call, but the method that is called must be defined in the superclass, that is, the method covered by the quilt class, but it still has to confirm the method based on the priority of the method invocation in the inheritance chain. The priority levels are: This.show (o), Super.show (O), This.show (Super) O, Super.show ((Super) O)

A slightly more complex example:

Class Human {public    void fun1 () {        System.out.println ("Human fun1");        Fun2 ();    }    public void Fun2 () {        System.out.println ("Human fun2");}    } Class Programmer extends Human {public    void fun1 (String name) {        System.out.println ("Programmer ' s Fun1");    } Public    void Fun2 () {        System.out.println ("Programmer ' s Fun2");}    } public class Test {public    static void Main (string[] args) {        Human Human = new Programmer ();        Human.fun1 ();    }     /* * Output:     *  Human fun1     *  Programmer ' s fun2     */}
    • Programmer in Fun1 (String name) and human in Fun1 (), except that the method name is the same but the parameters are different, so it is an overloaded relationship
    • The fun2 () in fun2 () and human in programmer are the same method, that is, programmer overrides Human's fun2 () method
    • HUMAN.FUN1 () calls the Fun1 () method in the parent class after the programmer object has been transformed to a human, and the Fun1 (String name) of the subclass is a different method
    • The Fun2 () method is called in Human's Fun1 (), which is overridden in programmer and is actually called the programmer () method in the referenced variable fun2

Package Test;class a {public    void func () {        System.out.println (' func in A ');}    } Class B extends A {public    void func () {        System.out.println ("Func in B");}    } Class C extends B {public    void func () {        System.out.println ("Func in B");}    } public class Bar {public    void Test (a a) {        a.func ();        System.out.println ("Test A in Bar");    public void Test (c c) {        c.func ();        System.out.println ("Test C in Bar");    }    public static void Main (string[] args) {        bar bar = new Bar ();        A = new A ();        b b = new B ();        c C = new C ();        Bar.test (a);        Bar.test (b);        Bar.test (c);        /*            func in a-test a in bar func-            b            Test A in bar            func-B            Test C in Bar         */    }}

In-depth understanding of Java object-oriented three major features encapsulating inheritance polymorphism

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.