5th Java Object-oriented

Source: Internet
Author: User

Java Object-oriented classes

A collection of a series of objects with the same properties and methods, which is a description of the object. The inner part of the class includes properties and methods two parts.

A class is a template for creating objects.

Naming conventions: Declarations of the Pascal Nomenclature class:
classdog{//Properties    PrivateString name; Private intAge ; Private floatheight; //Construction Method     PublicDog () {} PublicDog (String name,intAgefloatheight)        {super ();  This. Name =name;  This. Age =Age ;  This. Height =height; }        //Method     Public voideat () {System. out. println ("This dog can eat ..."); }        //Getter & Setter     PublicString GetName () {returnname; }         Public voidsetName (String name) { This. Name =name; }         Public intGetage () {returnAge ; }         Public voidSetage (intAge ) {         This. Age =Age ; }         Public floatgetheight () {returnheight; }         Public voidSetHeight (floatheight) {         This. Height =height; }    }
Property

In general, all properties are set to private (accessible only in this class)

A property is a description of an object's characteristics. When describing an object, you do not need to describe all of the characteristics of the object, just what you use to describe it.

Method

Methods include five parts: Qualifier + return value type + method name + parameter + method body

The parameter of the method at the time of definition is the formal parameter, which only plays the role of occupying position. A formal parameter is a local variable, and the scope is limited to the method body, and the method body is destroyed.

The arguments passed in when the method is called are called arguments, and its value is assigned to the parameter, which participates in the operation of the method body through the formal parameter. The transfer of this value is unidirectional, and only the arguments are passed to the formal parameter, and the value of the formal parameter is not passed to the argument after the method has finished executing.

Method overloading
    • Method name is the same
    • Method parameter list is different
    • Regardless of return value and qualified modifier
    • Occurs in the same class
 Public classcalc{//methods that are overloaded     Public intAddintNUM1,intnum2) {        returnnum1+num2; }    //parameter list is different, method name is the same     Public intAddintNUM1,intNUM2,intnum3) {        returnAdd (NUM1, num2) +num3; }    //parameter name and return value are different, method name is the same     Public floatAddfloatNUM1,floatnum2) {        returnnum1+num2; }    }
Construction method

Each class has its own method of construction. If you do not explicitly define a construction method for a class, the Java compiler will provide a default parameterless construction method for that class.

Several characteristics of the construction method:

    • The method name is the same as the class name
    • No return value
    • Automatically called when an object is created
    • A class has at least one to multiple constructor methods
Object

object is an entity used to describe objective things in the system, which is a basic unit of the system. An object consists of a set of properties and a set of services that operate on that set of properties.

An object is an entity that is described by a class and is an instantiation of a class.

Creating objects
    1. declaration : Declares an object, including the object name, object type,
    2. instantiation : Using the keyword new to create an object
    3. Initialize : When you create an object using new , the constructor is called to initialize the object

Example:

// invoking an parameterless construction method to instantiate an object New Dog (); // call the Take parameter constructor method to instantiate the object while initializing the object New Dog (" rhubarb "212.9f);
accessing objects

Because the properties of an object are set to private, they can only be accessed through the set and get methods.

Access member variables and member methods through the objects you have created, as follows:

Dog dog2 =NewDog ("Rhubarb",2,12.9f); System. out. println ("the name of the dog is:"+dog2.getname ()); System. out. println ("The age of the dog is:"+dog2.getage () +"years"); System. out. println ("the weight of the dog is:"+dog2.getheight () +"kg");

The printing results are as follows:

The dog's name is: The age of the Rhubarb dog is: 2 years old dog weight is: 9kg
Object-oriented basic features
    • Packaging
    • Inherited
    • Polymorphic
Object-oriented features
    • A common thought that fits people's thinking habits
    • Simplifying complex issues
    • From performer to conductor
Design process
    • Discovery Class
    • Discover the properties of a class
    • Methods for discovering classes
    • Optimization process

Design principles: Focus on the required properties and methods

Java Package Benefits:
    • Good encapsulation can reduce coupling
    • The internal structure of the class can be freely modified
    • More precise control of member variables is possible
    • Hide information, implement details
Access rights

In general, property values are all set to private, and properties are accessed through the set and get methods:

 Public classperson{PrivateString name; Private intAge ;?  Public intGetage () {returnAge ;    }?  PublicString GetName () {returnname;    }?  Public voidSetage (intAge ) {       This. Age =Age ;    }?  Public voidsetName (String name) { This. Name =name; }}

Some information about a class is hidden inside the class, not allowed to be accessed directly by the external program, but rather through the methods provided by the class for accessing and manipulating the hidden information.

Java inheritance

Inheritance is the child class inherits the characteristics and behavior of the parent class, so that the subclass object (instance) has the parent class's instance domain and method, or the subclass inherits the method from the parent class, so that the subclass has the same behavior as the parent class. At the same time, subclasses can expand on the basis of the parent class, adding their own unique properties and methods.

    • In Java, the extends keyword indicates the inheritance of a class to its parent class.
    • Subclasses will inherit all the properties and methods of the parent class except the private one (the private is still inherited, but cannot be used because of the scope)
    • Subclasses can be extended on the basis of a parent class
    • The order in which methods are executed in an inheritance relationship: The method is first looked up from the subclass, and if the method is not found in the subclass, then the parent class is searched.
    • Java is a single inheritance, a subclass can have only one parent class, and a parent class may have n subclasses
    • The constructor method cannot and does not need to be inherited because the constructor method of the parent class is called by default when the subclass's constructor is called
    • Initialization order of inheritance: Parent class construction Method--The parent class property is initialized--the subclass constructor Method--Class property class.
    • The Super keyword in Java represents the parent class, which can be used to invoke the common properties and methods of the parent class using Super
    • The This keyword in Java represents the current class, and all properties and methods in this class are accessible through the This keyword
classanimals{PrivateString name; //Parent Class Construction Method     PublicAnimals (String name) { This. Name =name; }         Public voideat () {System. out. println ("animals eat."); }}classDogs extends animals{//The subclass constructor method. The parent class does not have a parameterless constructor method, and the subclass must call the parent class constructor method when instantiating     PublicDogs (String name) {super (name); }     Public voidrun () {System. out. println ("dogs can run ."); }}

In the example above, animals is the parent class, and dogs is the subclass.

There is only one animals (String name) construction method in animals. In the subclass construction method, if you do not use super to call the parent class construction method, the compiler will call a super () method by default, but the compiler will make an error because the constructor does not exist in the parent class. At this point we are asked to call the parent class with the only parameter construction method.

The constructor method of the parent class must be called only once in the subclass construction method, and the location is before all operations of the method are constructed.

The Run method is an extension of the Dogs class on the basis of the animals class, and the Eat method is inherited in the Dogs class.

Examples of the use of dogs objects after inheritance:

New Dogs ("rhubarb");d ogs.eat ();d ogs.run ();

The printing results are as follows:

Animals eat, dogs run.
Override of Method

A subclass can override a method inherited from a parent class (Alt+shift+s, V), overriding a subclass object in a call that overrides the overridden method in the child class.

class extends animals{    public  Dogs (String name) {                super(name);            }     // overrides the parent class method, which is identified by the @verride     @Override    publicvoid  eat () {        System.out.println (" The dog will eat Bones ");}    }

When the Dogs.eat () method is called, the "Dog Eats Bones" is printed instead of "Animal eats".

Super, this keyword

Super represents the parent class, this represents the class

class extends animals{    public  Dogs (String name) {                super(name);    }    @Override    publicvoid  eat () {                System.out.println ("Dog eats Bones");    }          Public void animaleat () {        super. Eat ();          This . Eat ();    }}

The result of printing after calling the Animaleat method is:

Animals eat, dogs eat bones.
Final keyword

Final, meaning last, final.

    • A class that is final modified cannot be inherited
    • The final modified method cannot be overridden
    • Properties that are final modified can be modified (constants)
The difference between inheritance and composition

b extends a: Logically, it is the relationship of "B is a a". For example, a dog inherits from an animal, which means that the dog is an animal; clothes inherit from the goods, indicating that the clothes are a commodity.

Combination: Is a "A has B" relationship. In a class, you can use another object as your own property. For example, a person has a name, and the name itself is a string object, and we can go with it to describe a person.

Java polymorphism
    • Polymorphic is a reference to the parent class to execute the subclass object
    • Polymorphism must be built on the basis of inheritance (on the implementation of interfaces)
    • Polymorphic in the method call when the subclass now finds the method, no find then go to the parent class to find

Is polymorphic, that is, many forms.

Polymorphism is the ability of the same behavior to have many different manifestations or forms.

For example, two printers, one for monochrome printers and one for color printers. When we use a black and white printer, it will give us a black and white material, while the color printer is printed in color.

Abstract classPrinter {//How to print a parent class     Public Abstract voidprint ();}classBwprinterextendsPrinter {@Override Public voidprint () {System.out.println ("Printed a copy of the black and white material"); }}classColorfulprinterextendsPrinter {@Override Public voidprint () {System.out.println ("Printed a copy of the color material"); }} Public classMain { Public Static voidprint (Printer Printer) {printer.print (); }         Public Static voidMain (string[] args) {bwprinter bwprinter=NewBwprinter (); Colorfulprinter Colorfulprinter=NewColorfulprinter (); //print with a black and white printerprint (bwprinter); //print with a color printerprint (colorfulprinter); }}

Printing results are:

Printed a black and white material printed a color material
The advantages of polymorphism
    • Elimination of coupling between types
    • Replaceable
    • Scalability
    • interface of
    • Flexibility
    • Simplification of
Three necessary conditions for polymorphic existence
    • Inherited
    • Rewrite
    • Parent class reference to child class object

5th Java Object-oriented

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.