Javase Study Summary (v)--encapsulation, inheritance, polymorphism is very simple

Source: Internet
Author: User
Tags class definition getcolor

Directory

    • First, the package
      • 1.1, why need encapsulation
      • 1.2. Package Properties
      • 1.3. Auto Package properties
        • 1.3.1, creating a single
        • 1.3.2, Batch Creation
    • Ii. inheritance
      • 2.1. Java Inheritance Summary
      • 2.2. Why you need to inherit
      • 2.3. Implementing inheritance
      • 2.2. Features of Java inheritance
        • 2.2.1, transitivity
        • 2.2.2, single-sex
    • Third, the construction method
      • 3.1. Outline of construction method
      • 3.2, with parameters of the construction method
    • Iv. polymorphic
      • 4.1. LSP (the principle of substitution on the Richter scale)
      • 4.2, override (override)
      • 4.3. Multi-State implementation
    • V. Examples and Video downloads
    • Vi. Interview Questions

The three main features of Java object-oriented are: encapsulation, inheritance and polymorphism, which is the core of object-oriented programming.

First, the package

Simply said encapsulation is the same kind of things to the characteristics and functions of packaging, external exposure to the interface of the call.

Encapsulation: encapsulation, also known as information hiding, refers to the use of abstract data types to encapsulate data and data-based operations, making it an indivisible whole, the data is hidden inside the abstract data, as far as possible to hide the details of the data, only to retain some interfaces to the outside world to contact. This means that the user does not need to know the details of the implementation of the internal data and methods, just according to the interface left on the outside to operate on the line.

Benefits of Encapsulation:

1) achieve a professional division of labor

2) Good encapsulation can reduce coupling

3) The structure within the class can be freely modified

4) More precise control of the members

5) hiding information, implementing details

1.1, why need encapsulation

Define a student class that defines the height of the student in the class.

Student class:

Package com.zhangguo.c41;/** Student Class */public class Student {    /** height */public    int height;        /** Display *    /public void Show () {        System.out.println ("Height:" +this.height+ "cm");}    }

School type:

Package Com.zhangguo.c41;public class School {public    static void Main (string[] args) {                Student tom=new Student () ;        tom.height=189;        Tom.show ();                Student rose=new Student ();        rose.height=-398;        Rose.show ();    }}

Operation Result:

From the example, it can be seen that the height of the student's object is -398cm, which is obviously unscientific, encapsulating attributes and providing access to the external interface.

1.2. Package Properties

If you want to protect the height property, you can modify its access modifier to private, as follows:

    /** Height */    private int height;

The error:

Because it is private, only this class can be accessed normally, external access is not, you can define the properties to achieve access control and encapsulation functions, as follows:

Student class

Package com.zhangguo.c41;/** Student Class */public class Student {    /** height */    private int height;    /** returns the height attribute *    /public int getheight () {        return this.height;    }    /**     * Set height Property     *      * @throws Exception     *    /public void setheight (int height) {        // If the parameter height is greater than 260 or less than 0        if (Height < 0 | | height > 260) {            //Output error message            System.out.println ("Height can only be between 0-260") ;        } else {            this.height = height;        }    }    /** Display *    /public void Show () {        System.out.println ("Height:" + this.height + "cm");}    }

Student class:

Package Com.zhangguo.c41;public class School {public    static void Main (string[] args) {                Student tom=new Student ();        Tom.setheight (189);        Tom.show ();                Student rose=new Student ();        Rose.setheight ( -398);        Rose.show ();    }}

Operation Result:

GetXXX () obtained, setxx (parameter) settings

You can debug the view.

1.3. Auto Package properties

If you define very many properties in a class, manual encapsulation is cumbersome, with 1 properties corresponding to 2 methods and 1 get,1 set. There are features in eclipse that automatically encapsulate attributes, as follows:

1.3.1, creating a single

Hover over the property and click "Create getter and setter for XXX"

1.3.2, Batch Creation

Result of the build:

Package com.zhangguo.c41;/** Dog */public class Dog {    /** name */    private String name;    /** Prices */    private float price;    /** Color */    private String color;        Readable writable public    float GetPrice () {return price        ;    }    public void Setprice (float price) {        This.price = Price;    }    Read-only public    String GetName () {        return name;    }    Write only public    void SetColor (String color) {        This.color = color;    }    }
Ii. Inheritance 2.1, Java Inheritance Summary

Java inheritance is one of the most prominent features of object-oriented. Inheritance is the derivation of new classes from existing classes, which can absorb data properties and behaviors of existing classes, and can extend new capabilities. Java does not support multiple inheritance, single inheritance makes Java inheritance simple, a class can have only one parent class, easy to manage programs, the parent class is the generalization of subclasses, subclasses are the specialization (materialization) of the parent class

Parent class (base class): Human subclass (Derived): Student

The student inherits, the person derives the student.

Inheritance is expressed as an intersection between object classes, which enables a class of objects to inherit data members and member methods of another class of objects. If Class B inherits from Class A, then the object belonging to B has all or part of the nature of Class A (data attributes) and functions (operations), we call the inherited class A as a base class, a parent class, or a superclass, whereas inheriting Class B is a derived class or subclass of a.

Inheritance avoids repeating descriptions of common features between general classes and special classes. At the same time, inheritance can clearly express the conceptual scope in which each common feature is adapted--attributes and operations defined in a generic class are adapted to the class itself and to all objects of each layer of special classes below it. The application of the principle of inheritance makes the system model more concise and more clear.

Java uses the extends keyword to identify inheritance.

2.2. Why you need to inherit

Dog Dogs

Package com.zhangguo.c42;/** Dog */public class Dog {    /** name */public    String name;    /** Color */public    String color;    /** Price */public    double value;        /** Display information *    /public void Show () {        System.out.println ("Name:" +name+ ", Color:" +color);}    }

Cat Cat

Package com.zhangguo.c42;/** cat */public class Cat {    /** name */public    String name;    /** Color */public    String color;    /** weight */public    double weight;        /** Display information *    /public void Show () {        System.out.println ("Name:" +name+ ", Color:" +color);}    }

Zoo Park

Package com.zhangguo.c42;/** Zoo */public class Zoo {public    static void Main (string[] args) {        dog dog=new dog (); 
   dog.name= "Chihuahua dog";        Dog.color= "Green";        dog.price=19800.7;        Dog.show ();                Cat cat=new Cat ();        Cat.name= "Persian cat";        Cat.color= "Red";        cat.weight=18.5;        Cat.show ();            }}

Operation Result:

The above code realizes the basic function, but has the question, mainly: Name,color,show repeats, if the system animal class again increases will keep repeating, the repetition will bring the inconvenience to revise, the inconvenience maintenance question.

2.3. Implementing inheritance

To solve the above problem, you can use inheritance to achieve the purpose of code reuse.

Animal animals:

Package com.zhangguo.c43;/** Animal */public class Animal {    /** name */public    String name;    /** Color */public    String color;        /** Display information *    /public void Show () {        System.out.println ("Name:" +name+ ", Color:" +color);}    }

Dog Dogs:

extends Animal {    /** price */public    double value;}

Cat Cat:

Package com.zhangguo.c43;/** cat */public class Cat extends Animal {    /** weight */public    double weight;}

Zoo Zoos:

Package com.zhangguo.c43;/** Zoo */public class Zoo {public    static void Main (string[] args) {        dog dog=new dog (); 
   dog.name= "Chihuahua dog";        Dog.color= "Green";        dog.price=19800.7;        Dog.show ();                Cat cat=new Cat ();        Cat.name= "Persian cat";        Cat.color= "Red";        cat.weight=18.5;        Cat.show ();            }}

Operation Result:

As seen from the example, the dog does not define a color property, but can be called in use because the dog inherits the parent class animal, and the non-private members of the parent class inherit the quilt class. If you define other animal classes again, you do not need to define name,color and show methods again.

2.2. Feature 2.2.1, transitivity of Java inheritance

If Class C Inherits Class B and Class B inherits Class A (multiple inheritance), then Class C has properties and methods inherited from Class B, as well as properties and methods inherited from Class A, and can have its own newly defined properties and methods. Inherited properties and methods, although implicit, are still properties and methods of Class C.

2.2.2, single-sex

If Class B inherits from Class A, then building Class B requires only a few more features (data members and member methods) that are different from the base class (Class A). This method can reduce the redundancy of code and data, and greatly increase the reusability of the program.

Iii. Construction Method 3.1, outline of construction method

A), the constructor method is the method that is called when the object is created, (instantiation, New), the Destructor method

b), the constructor method name is the same as the class name (such as the book class construction method name must book)

c), construction method no return type () public book () {}

D), a class if you do not define a constructor method will default to a parameterless construction method, if the user has customized the construction method is no longer the default definition of the non-parametric construction method

Package com.zhangguo.c44;/** car */public class Car {        /**/    private int speed;        Construction method Public    Car () {        System.out.println ("Install tires");        SYSTEM.OUT.PRINTLN ("Installing the Steering Wheel");        this.speed=230;    }    }

Test

Package Com.zhangguo.c44;public class carclient{public    static void Main (string[] args) {                        car c1=new car (); C14/>car c2=new Car ();            }}

Results:

3.2, with parameters of the construction method

A), the parameters of the construction method are the same as the common method

b), the construction method allows overloading (the same name method different number of parameters or types)

c), the constructor of the parent class is called by default when the subclass is created, typically without a parameter construct

d), use Super to invoke the constructor specified by the parent class, when calling the constructor method of the parent class in the child class must be in the first row

e), use Super to invoke any public member in the parent class

Package com.zhangguo.c44;/** vehicle */public class Car {        /** speed */public    int velocity        ; Construction method Public    Car (int _speed) {        this.speed=_speed;    }        Non-parametric construction method public    Car () {        this.speed=100;    }        /** start *    /public void start ()    {        System.out.println ("Speed:" +this.speed)    ;    }

Test:

Package Com.zhangguo.c44;public class carclient{public    static void Main (string[] args) {                        car c1=new car (99); c21/>c1.speed=100;        C1.start ();                Car c2=new car (n);        C2.start ();                Car c3=new car ();        c3.speed=198;        C3.start ();            }}

Results:

Package Com.zhangguo.c44;class a{public    A () {        System.out.println ("a");}    } Class B extends a{public    B () {        System.out.println ("B");}    } public class Student {public    static void Main (string[] args) {        b b=new b ();}    }

Operation Result:

A

B

Animals:

Package com.zhangguo.c47;/** Animal */public class Animal {public        Animal () {    } public        Animal (String name) {        SetName (name);    }        /** Name attribute */    private String name;    /**     * Get name     *    /Public String getName () {        return name;    }    /**     * Set name     *    /public void SetName (String name) {        this.name = name;    }        /** Show *    /public void Show () {        System.out.println ("This is" +this.name);}            }

Dog:

Package com.zhangguo.c47;/** dogs */public class Dog extends Animal {public    Dog () {    } public dog    (String name, String color) {        super (name);        SetColor (color);    }        /** Color */    private String color;    Public String GetColor () {        return color;    }    public void SetColor (String color) {        This.color = color;    }        /** overrides the Show method of the parent class because there is also the same show method in the parent class *    /public void Show () {        super.show ();        System.out.println ("color:" +color);    }        Annotation    @Override public    String toString () {        return name: "+getname () +", Color: "+getcolor ();    }        }

Zoo:

Package Com.zhangguo.c47;public class Zoo {public    static void Main (string[] args) {        dog dog1=new dog ("Chihuahua", "Red") ;        System.out.println (Dog1.tostring ());                Dog Dog2=new Dog ("Big Doll", "Blue");        System.out.println (Dog2.tostring ());}    }

Results:

Iv. polymorphic

Object-oriented polymorphism is mainly embodied in: rewriting and overloading, which have been explained in detail in the previous course.

4.1. LSP (the principle of substitution on the Richter scale)

LSP Full name Liskov Substitution Principle, Chinese name means the Richter substitution principle. The LSP is about the relationship between the base class and the subclass. Only when the relationship exists, the Richter substitution relationship exists.

Subclasses must be able to replace the parent class.

The amount of information for a subclass must be greater than the parent class. The mouse's son can make a hole, and the mouse's son must replace the mouse's father.

Package Com.zhangguo.c45;class A{}class B extends A{}public class Student {public    static void Main (string[] args) {
   a a1=new B ();        Object a2=new A ();                Task (New B ());    }        public static void Task (a a) {            }}

The subclass object can be substituted in the code where the parent class object is required.

4.2, override (override)

In Java, subclasses can inherit methods from the parent class without having to rewrite the same method. But sometimes subclasses do not want to inherit the parent class's methods, but want to make some changes, which requires a method of rewriting. Method overrides are also called method overrides.

Package Com.zhangguo.c46;class car{public    void Start ()    {        System.out.println ("Car Running");}    } Class Supercar extends car{public    void Start ()    {        System.out.println ("car in Flight");}    } public class Student {public    static void Main (string[] args) {        Car car=new supercar ();        Car.start ();    }}

Operation Result:

The car is flying.

4.3. Multi-State implementation

Different subclass objects of the same class produce different results called polymorphism for calls to the same method.

Actor

Cook

Barber

He is a subclass of person, but they do not behave the same when they hear cut.

Package com.zhangguo.c47;/** people */public class Person {public        void cut () {    } public        static void Main (string[] args) {person        player=new player ();        Person Cooker=new cooker ();        Person Cuter=new cuter ();                Player.cut ();        Cooker.cut ();        Cuter.cut ();    }} /** actor */class Player extends person{    /** rewrite *    /public void Cut () {        System.out.println ("stop Acting");}    } /** Chef */class Cooker extends person{    /** rewrite *    /public void Cut () {        System.out.println ("Start chopping");}    } /** Chef */class cuter extends person{    /** rewrite *    /public void Cut () {        System.out.println ("Start hair Cut");}    }

Operation Result:

The specific type of reference variable defined in the program and the method call made through the reference variable are not deterministic during programming, but are determined during the program's run, that is, the instance object of the class to which the reference variable is inverted, and the method call that the reference variable emits is the method that is implemented in the class. Must be determined by the time the program is running. Because when the program is run to determine the specific class, so that, without modifying the source code, you can bind the reference variable to a variety of different class implementations, resulting in the invocation of the specific method of the reference change, that is, do not modify the program code can be changed when the program runs the specific code, so that the program can select multiple running state, This is polymorphism. Polymorphism enhances the flexibility and extensibility of the software. Xiao Li likes to listen to birds singing {Sparrow, Cuckoo, parrot}

Xiao Li: The bird outside the window, sing me a song.

1. (Bird bird = new Sparrow)?

2. (Bird bird = new cuckoo)?

3. (Bird bird = new Parrot)?

Bird: bird.sing () ~~~~~

Xiao Li: Birds sing well, what kind of bird are you?

Bird: Bird.shape ()

Xiao Li: (---If the blue character above defines 3, is a parrot) haha! Oh, you're a parrot!

So, the process of polymorphism is essentially an abstract instruction that allows a group of individuals with the same behavior to work together with different content in a single process.

The rewriting, overloading and dynamic connection of the method are polymorphic.

Java introduces the concept of polymorphism, one of the reasons is that it is in the inheritance of the class and C + +, which allows multiple inheritance, which does give it a very powerful function, but the complex inheritance of the C + + developers have also brought greater trouble, in order to avoid the risk, Java only allow single inheritance, There is a is-a relationship between the derived class and the base class (that is, "cat" is a "animal"). Although this ensures that the inheritance relationship is simple and clear, but there is bound to be a large number of functional limitations, so Java introduced the concept of polymorphism to compensate for this shortcoming, in addition, abstract classes and interfaces are also important means to solve the single inheritance restrictions. At the same time, polymorphism is also the essence of object-oriented programming.

To understand polymorphism, you first need to know what is "upward transformation".

I defined a subclass cat, which inherits the animal class, which is the parent class of the former. I can pass

Cat C = new Cat (); To instantiate a Cat object, this is not difficult to understand.

But when I define this: Animal a = new Cat ();

What does that mean?

Very simply, it means I have defined a reference to the animal type, pointing to the new cat type object. Because Cat is inherited from its parent class animal, references to animal types can point to objects of the cat type. So what's the point of doing that? Because subclasses are an improvement and an extension to the parent class, the generic subclass is more powerful than the parent class, the property is more unique than the parent class, and the object that defines a reference to a child class of a parent class can use both the powerful functions of the subclass and the commonality of the parent class. So

The parent class reference can only invoke methods and properties that exist in the parent class, and cannot invoke the extended part of the subclass, because the parent class reference refers to the parent class that inherits from the child class object of the heap, but if you force the superclass to be converted to subclasses, you can call methods that are newly added in the subclass and that the superclass does not. )

At the same time, a method in the parent class can be called by a reference to the parent class only if it is defined in the parent class and is not overridden in the subclass.

For a method defined in a parent class, if the method is overridden in a subclass, then a reference to the parent class type invokes this method in the subclass, which is the dynamic connection.

V. Examples and video downloads Vi. interview questions

1. What keywords are used to define the package?

Package Com.zhangguo.projectA

2. What keywords are used in the import package?

Import Com.zhangguo.projectA. Class Import Com.zhangguo.projecta.*

3. What should I declare if I want to import all the classes under Com.zhangguo.project?

Import com.zhangguo.project.*

4. Can a static method invoke other non-static methods in the same class directly?
No, call by object

5. Can a non-static method invoke other static methods in the same class directly?

Same class: Call directly

Different classes: called with the class name, such as the class name. Member Name

Package Com.gdnf.java.d3;public class Student {public    static void Main (string[] args) {        //static direct call to static        int i= Add (+);        System.out.println (Add (i,100), 7));                Static instance calls non-static        Student stu=new Student ();        System.out.println (Stu.calc (1,2,add (9,91));    }        public int calc (int i,int j,int k) {        //non-static direct call static        return  Add (Add (i,j), k);    }        /**     * Addition Operation     * @param x first parameter     * @param y second argument     * @return Add result */public    static int Add (int x, int y) {        return x+y;    }}

Operation Result:

6. Define a car, define the property speed and vehicle name in the car, package speed and name, and ask for speeds between 50-300; Define the Start method output car name and speed. Test the defined class Testcar;

7, please define the parent class (person), attribute name (name) and gender (sex), method Hello method output name and gender; subclass student student and teacher teacher respectively heir,

Student has the attribute class (Classno), the teacher has the attribute seniority (teachlen), tests the well-defined class Testschool;

8, Java object-oriented three major features are: encapsulation, inheritance and polymorphism

9, there is a class definition is this: public class Cat extends Animal, where Cat is a cat, Animal is an animal, ask the base class is, sub-class is, the base class is also called Why? What do subclasses say?

The base class animal, the subclass cat, the base class are also called the parent class, the subclass is also called the derived class

10, the following class (Phone:product,book:product) is known, please complete the inheritance of another class (book, add attribute author), implement the encapsulation of price

Product.java

Package com.zhangguo.c44;/** Product */public class Product {    /** prices */    private double price;    /** Get Price *    /public double GetPrice () {        return value;    }    /** Set Price */public    void Setprice (double price) {        if (value >= 0) {            this.price = prices;        } else {            SYSTEM.OUT.PRINTLN ("Price must be >=0");}    }    /** Display *    /public void Show () {        System.out.println (the price of the product is: "+ prices);}    }

Book.java

Package com.zhangguo.c44;/** books inherit products */public class Book extends product {    /** author properties */    private String Author;
   public String Getauthor () {        return author;    }    public void Setauthor (String author) {        this.author = author;    }}

Phone.java

Package com.zhangguo.c44;/** phone */public class Phone extends Product {    /** brand * * Public    String brand;} Class Vivo extends phone{    }

Store.java

Package Com.zhangguo.c44;public class Store {public    static void Main (string[] args) {        //define book object, set price to 100, Show Price book Book        = new book ();        Book.setprice ( -100);        Book.show ();                Vivo vivo=new Vivo ();                    }}

Javase Study Summary (v)--encapsulation, inheritance, polymorphism is very simple

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.