Java Object-oriented inheritance

Source: Internet
Author: User

Inheritance is also an important object-oriented feature, inheritance is a class-to-class relationship, in layman's terms the dog belongs to the animal class, then the dog class inherits the animal class.

Inheritance in Java is single-inheritance, and a class can inherit only from one parent class

After the subclass inherits the parent class, the subclass has all the properties and methods of the parent class, except the private one, the advantage is that it can improve the reusability of the code, the simple inheritance example is as follows:

1  Public class extends Animal {2     // The Dog class inherits all the non-private properties and methods in the animal class and can be used  directly 3 }

It's pretty simple to use inheritance.

  Method overrides

If the subclass is not satisfied with the method that inherits the parent class, then it is possible to override the method inherited by the parent class, and when the method is called, the method of the subclass is called first, such as the above instance, for example, Animal has a way of eating, but the dog also has its own way of eating, not too satisfied with the method defined Then you can rewrite the animal to eat this way

The overriding syntax rule is that the return value type, method name, parameter type, number of arguments, and order must be consistent with the method inherited in the parent class before the method override can be implemented

  Initialization Order of inheritance

Inheritance is initialized in order, and when we instantiate a subclass object, how does the concrete class load?

Because the attributes of the parent class are needed in the subclass, the order is to initialize the parent class first and then initialize the subclass;

And initialize the properties in the object first, and then execute the constructor method in the class, in order to initialize;

So the final initialization sequence should be: Initialize parent class properties, execute Parent class constructor method, initialize subclass property, and execute subclass constructor method

  Use of the final keyword

Final literal meaning is final, final, non-modifiable, so final modification modifies a quantity that cannot be changed

In fact, the final keyword can be decorated with classes, methods, properties, local variables

1. When final modifies a class, the class is not allowed to be inherited

All member methods in the final decorated class are also implicitly set to the final type, but the member properties do not change;

Be careful when you use the final modifier class, unless the class is later determined not to be inherited, or to ensure security, it is not generally set to final

The general wording is: Public final class class name {}

2. When final modifies a method, the method is not allowed to be overridden

The private-modified method is implicitly set to final

Example: Public final float Method name (parameter) {}

3. When final property is modified

By default, member properties are implicitly assigned an initial value of 0, but when the final keyword is decorated, the system does not initialize the assignment, so we must assign a value to the variable at initialization time or assign a value to the property in the constructor, both of which must be selected, or the compiler will give an error, Once an attribute is initialized, the value of the property (or the object to which it points) cannot be changed, that is, the member property becomes a constant

For example: private final int a = 3;

Or: Final Object obj = new Object ();

4. When final modifies local variables

Final modified variable, which can only be assigned once, and must be assigned when the variable is declared, and then become a constant

For example: Final float b = 3.1f;

  Use of the Super keyword

The Super keyword is generally used inside subclasses and can represent objects of the corresponding parent class, with the following two points:

1. Accessing the parent class object properties

In a generic subclass, if you define a property that has the same name as the parent class, Access takes precedence over the properties of the subclass, and you can access the properties in the parent class by using Super. Parent class Properties

2. Methods to access the parent class object

If the method of the parent object is overridden by the quilt class, the subclass object calls the overridden method in the subclass by default, and if the method needs to call the parent class, it can use Super. Method Name () to access the overridden method in the parent class

In addition, we know that subclasses will invoke the constructor of the parent class when instantiating the object, so this is the equivalent of implicitly using the Super keyword to see a simple example:

Parent Class Animal:

1  Public class Animal {2     // Parent Class Construction Method 3      Public Animal () {4         System.out.println ("Animal constructor method is called"); 5     }6 }

  Sub-Class Dog:

 1  public  class  Dog extends   Animal { 2   Subclass construction method  3   Dog () { 4  super  (); //  The compiler automatically adds the Super keyword, calling the constructor method of the parent class  5  System.out.println ("The Dog class constructor method is called"  6   7  }

The output of this program is sure to know that the constructor of the parent class is executed after the construction method of the subclass is executed, and the compiler automatically adds super () in the first row of the subclass constructor method, that is, the 4th row of the dog class, so that the constructor method of the parent class is called, so that the parent class is executed. If we manually add super () then the system will not be added again;

According to the above, we know that a class can be defined in a number of construction methods including a parameter, no argument, if the parent class defines both a constructor method and a parameterless constructor, and we do not show in the subclass constructor method which constructor method is called in the parent class, Then the system will default to the constructor of the parent class without parameters, that is, through the super () method, if we show the call, must be placed in the subclass of the first line of construction method to call, and can be passed in super () parameters;

If we only defined a constructor method in the parent class that was described earlier in this article, we said that at this point the system does not initialize an parameterless constructor for us, and we do not see the use of super () in our subclasses to call us in the parent class, and the compiler implicitly calls the no-argument construction method to fail. So I will make a mistake;

  The object class in Java

In the Java world, the object class is the parent of all classes, and the ancestor of all classes, like the universe in our lives, if a class does not inherit from that class with the Extends keyword explicit table name, then he must inherit directly from the object class

Object provides a number of methods that can be used directly

1. ToString ()

The ToString method is a method that Java defines for ease of output, a method that is automatically called for us to manipulate strings, usually without intervention, and in many ways the ToString method is rewritten;

Use System.out.println (); The ToString method is also automatically used when outputting, and if we output an object directly instead of a string, we will see the compiler output:

[Email protected]

In this case, it is obvious that @ front is the package name, then we call the object hash code after the @, the hash code is a string generated by the hashing algorithm, identifies the object in memory storage address, hash code can uniquely distinguish an object;

If we want the ToString method to output the object's property values, then we can override the ToString method, and Eclipse can easily override the ToString method by clicking the toolbar: source->generate ToString () ... You can quickly rewrite the ToString method according to our needs, and the ToString method can return a string, the default code is as follows:

1 @Override 2  Public String toString () {3     return "Animal [age=" + Age + "]"; 4 }

Where animal is the class name, and age is a property in the class so that it can output an attribute in the object, which is, of course, just an example of what we can do with an object. The way the property is output

2, Equals ()

The purpose of the Equals method is to compare whether the reference of the object points to the same memory address, and the return value is a Boolean value

For example, we created a class dog before, and we can create an object of the dog class: Dog dog = new Dog (), so that a dog object is created, so strictly speaking, the dog is not an object in itself, but instead points the dog to the address of an object in memory. So dog is just a reference to an object, and we manipulate the various properties and methods indirectly by reference;

So the essence of equals is to compare whether a reference to two objects is the same area of memory

But what we often use is not to compare memory areas, we think that all the properties and methods within the two objects are the same so that two objects are what we think of as "equal", and do not care whether or not to point to the same piece of memory area, this time object provides the method is not suitable for our needs, Now it's time to rewrite the Equals method.

By default, we use two objects from the dog class to test:

1  Public classInitail {2      Public Static voidMain (string[] args) {3Dog Dog1 =NewDog ();4Dog dog2 =NewDog ();5         //compares two objects with the default Equals method6         if(Dog1.equals (dog2)) {7System.out.println ("Two objects are the same");8}Else{9System.out.println ("Two objects are not the same");Ten         } One     } A}

This result is obviously output: two objects are not the same, even if all the property values in Dog1 and dog2 are exactly the same, because the system has opened two different memory areas for DOG1 and dog2 references in memory

If we compare the Equals method to = =, we know that for Java basic data types, = = Determines whether the values of the two basic properties are equal, regardless of the memory address, but when you use = = To determine two reference data types, He is also a comparison of two references to the memory area is the same area, so with = = and the above output is the same

So if you want to achieve a comparison of the values of only two object references, regardless of whether they point to the same memory address, then override the Equals method, and Eclipse can quickly rewrite the Equals method directly, click menu: Source->generate Hashcode () and Equals () ... You can quickly rewrite the hashcode generation algorithm and the Equals method, after which we can delete the Hashcode method, leaving only the Equals method, as follows:

1  Public classDogextendsAnimal {2      Public intAge = 20 ;3     4 @Override5      Public Booleanequals (Object obj) {6         if( This==obj)7             return true;8         if(obj = =NULL)9             return false;Ten         if(GetClass ()! =Obj.getclass ()) One             return false; ADog other =(Dog) obj; -         if(Age! =other.age) -             return false; the         return true; -     } -}

Now we have only defined an attribute age in the dog object, so overriding the Equals method is relatively straightforward, because the calling method is Dog1.equals (DOG2), so this is the Dog1 object, and the incoming parameter dog2 is the parameter in the method. So it's reasonable to write equals in the dog class.

The first comparison this==obj, that is, if the dog1 and Dog2 point to the same memory area, then obviously two objects are equal, so directly return true;

Otherwise, if obj is null or does not point to any memory address, then it is definitely not equal and returns false directly;

Otherwise, through the GetClass method to determine whether the class object is equal, the GetClass method is the code information of an object, the property type and distribution, in layman's terms, we are comparing the two objects inside the property and method type, decoration and other information is consistent, And our normal use of the object belongs to the object of the class, we generally manipulate the property value, and then calculate the results we need to focus on the data information of the property, so the class object and class instantiation object to distinguish clearly

We then convert the Dog2 object, which is the obj parameter object, to the dog type, so that the conversion is safe, and then compare the property values to the same, and return FALSE if the property values are not the same.

If the above steps are validated, the two object values must be equal, so a true value is returned, so that the equals override is achieved to compare object values.

The above is the simple application of inheritance and a little in-depth understanding of inheritance, if there is a new experience to continue to add

  

Java Object-oriented inheritance

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.