Java Core technology-inheritance

Source: Internet
Author: User
Tags modifier modifiers visibility wrapper

Class 1, superclass, and subclass

The "is-a" relationship is an obvious feature of inheritance.

1.1 Defining subclasses

Keyword extends represents inheritance

The keyword extends indicates that the new class being constructed derives from an existing class, that the existing class is called a superclass, that the new class is called a subclass, and that the sub-analogy superclass has more functionality.

You only need to point out the differences between the subclasses and the superclass when you extend the superclass by extending the subclasses. Therefore, when designing a class, you should put a common method in the superclass and put a special-purpose method in the subclass.

1.2 Overriding methods

A private domain inherited by a subclass can only be accessed by means of a superclass. (Super keyword)

The difference between super and this:

The Super keyword is not a reference to an object, and you cannot assign super to another object variable, it is just a special keyword that instructs the compiler to call a superclass method.

You can increase the domain, add methods, or override the superclass in a subclass, but you cannot delete any inherited fields and methods.

1.3 Sub-class constructors

Because the constructor of the subclass cannot access the private domain of the superclass, the private domain must be initialized with the superclass's constructor, and we can implement the call to the Super class constructor with super.

The statement that uses super to call the constructor must be the first statement of the subclass constructor.

Two uses of the keyword this: 1. Refer to implicit arguments; 2. Call the other constructors of the class.

Two uses of the keyword Super: 1. Method of calling the superclass; 2. Calling the constructor of a super class

Same point: The statement that invokes the constructor can only appear as the first statement of another constructor.

。 The phenomenon of being able to automatically select which method to invoke at run time is called dynamic binding.

1.4 Inheritance Hierarchy

A collection of all classes derived from a common superclass is called an inheritance hierarchy, and the path from a particular class to its ancestor is called the inheritance chain of that class.

1.5 polymorphic

An object variable can indicate that a number of actual types of phenomena are known as polymorphic

A simple rule that determines whether an inheritance relationship should be designed: the "is-a" rule, which indicates that each object of the subclass is also an object of the superclass.

The object variable is polymorphic.

1.6 Understanding Method Invocations

When invoking the F method of an object of Class C:

1. Method table for extracting the actual type of the object: The compiler enumerates all methods named F of Class C and the method named F with the Access property in its superclass

2. Overload resolution: Find a method that exactly matches the parameter type. (allows subclasses to define the return type of the overriding method as a subtype of the original return type).

3. Static binding : If it is a private method , astatic method , afinal method , or a constructor , Then the compiler will be able to know exactly which method should be called (otherwise 4)

4. Dynamic binding: The class method that the virtual machine calls the most appropriate for the actual type of the referencing object.

Important features of dynamic binding: You can extend a program without modifying the existing code.

When overriding a method, the subclass method cannot be less than the visibility of the superclass method (the superclass method is public and the subclass method cannot omit the public modifier).

1.7 Block Inheritance: final Classes and methods

Classes that do not allow extensions are called final classes, and the final method does not allow child class overrides (all methods in the final class are automatically called final methods, excluding fields)

For example, the String class is the final class, and the GetTime and SetTime methods in the Calendar class are declared final.

Inline: If a method is short, often called, and not really overwritten, the instant compiler can optimize it (e.getname ()->e.name)

1.8 Coercion of type conversions

A reference to a subclass is assigned to a superclass variable, which is allowed by the compiler. However, a reference to a superclass is assigned to a subclass variable, and a type conversion is required.

Type conversions are required only if you need to use a method that is specific to a subclass.

A good design habit: Before you make a type conversion, check to see if you can successfully convert. (using the instanceof operator)

Summarize:

* Type conversions can only be performed within an inheritance hierarchy.

* Before you convert a superclass to a subclass, you should check with instanceof.

1.9 Abstract class

The class that is decorated with the abstract keyword is called an abstract class and can contain no abstract methods.

A class that contains one or more abstract methods must itself be declared abstract, and abstract classes can contain specific data and methods in addition to abstract methods .

1.10 Protected Access

If you want some methods in a superclass to allow access to the quilt class, or to allow a method of a subclass to access a domain of a superclass, you can declare these methods or fields as protected.

The 4 access modifiers that Java uses to control visibility:

1.--private only visible to this class

2. Visible to all classes--public

3. Visible to this package and all subclasses--protected

4. Visible to this package--default, no modifiers required

2 Object: Super class for all classes

The object class is the ancestor of all classes in Java, and in Java each class is extended by it.

Only the base type in Java is not an object.

2.1 Equals method

The Equals method in the object class is used to determine whether an object is equal to another object (by means of the same reference)

In general, it is necessary to override this method of judgment, judging by the equality of two object states.

To prevent null situations, you need to use the Object.Equals (A, B) method. If all two parameters are null, return True if one of the null returns is False, and if none of the two parameters are null, call A.equals (b).

2.2 Equality Test and inheritance

For fields of an array type, you can use the static Arrays.equals method to detect whether the corresponding array elements are equal.

2.3 Hashcode Method

A hash code is an integer value that is exported by an object.

Because the Hashcode method is defined in the object class, each object has a default hash code. Its value is the storage address of the object.

If you redefine the Equals method, you must redefine the Hashcode method.

Use the Object.hash method to calculate the hash for each domain value.

Object.hash (Name,salary,hireday)

The domain value used in the comparison in equals should be the same as in Hashcode.

2.4 ToString Method

The object class defines the ToString method, which is used to print the class name and hash code that the output object belongs to.

The vast majority of ToString methods follow this format: The name of the Class (GetClass (). GetName ()), followed by a value of the field in which the square brackets are lavish.

The array inherits the ToString method of the object class, which is fixed by invoking a static arrays.tostring or Arrays.deeptostring method.

It is strongly recommended that you add a tostring method for a custom class that does not have a

3 Generic Array list

ArrayList is a generic class that takes a type parameter.

Use the "diamond" syntax to omit the right-hand type parameter.

Once you can confirm that the size of the array list no longer changes, you can call the TrimToSize method. The garbage collector will reclaim excess storage space.

3.1 Accessing array list elements

Manipulate the list of arrays using the GET, set, add, remove methods

If the array stores more elements and often needs to insert and delete elements in an intermediate location, you should consider using a linked list.

Arrays and array list comparisons:

* Do not indicate the size of the array

* Add any number of elements to the array using add

* Use size () instead of length to calculate the number of elements

* Access elements using A.get (i) instead of a[i]

3.2 Typing compatibility with original array list

Due to compatibility considerations, after the compiler checks for type conversions, if no rules are found, all typed array lists are converted to the original array list.

When you cross-operate with legacy code, look at the compiler's warning prompts and make sure that these warnings do not cause too serious consequences.

4 Object wrapper and Auto Boxing

All basic types have a class corresponding to them, which are called wrappers.

The object wrapper class is immutable, and once the wrapper is constructed, the value of the wrapper is not allowed to change.

The object wrapper class is the final class and cannot define their subclasses.

Because each value is wrapped separately in the object, the efficiency of the arraylist<integer> is much lower than the int[] array.

Auto-Boxing: When an int value is assigned to an integer object

Automatic unpacking: When an integer object is assigned to an int value

Boxing and unpacking are compiler-approved, not virtual machines.

There is another benefit to using the numeric object wrapper: You can place some basic methods in the wrapper (Integer.parseint (s))

5 Methods with variable number of parameters

Public PrintStream printf (String fmt,object ... args)

Here's the ... is part of the Java code, which indicates that this method can receive any number of objects.

The compiler converts the method, binds the mutable parameter to the object[] array, and automatically boxing when necessary.

A method that already exists and the last parameter is an array can be redefined as a mutable parameter method.

6 enumeration Classes

public enum Size {small,medium,large};

This declaration defines an enumeration class, which has four instances.

When comparing the values of two enumerated types, never use equals, but directly using = =

All enum classes are subclasses of the Enum class

ToString ()-Returns the enumeration constant name

Inverse method of ValueOf ()-tostring ()

VALUES ()-Returns an array containing all the enumeration values

Ordinal ()-Returns the position of the enumeration constant

7 Reflection

The reflection mechanism can be used to:

* Ability to analyze classes at run time

* Viewing objects at run time

* Implementation of common array operation code

* Use Method Object

7.1 Class

During a program run, the Java Runtime system always maintains a type identity known as the runtime for all objects. This information tracks the classes that each object belongs to. The virtual machine uses the run-time type information to select the appropriate method to execute.

There are three ways to get class classes :

The GetClass () method in the 1.Object class returns an instance of the class type.

Class C1 = E.getclass ();

2. Call the static method forname to obtain the class name corresponding to the classes object;

Class C1=class.forname (className);

3. If T is an arbitrary java type, T.class will represent the matching class object.

Class C1=random.class;

The most common class method is GetName, which returns the name of the class.

A class object actually represents a type, and this type may not necessarily be a class. For example, int is not a class, but Int.class is an object of type class.

For historical reasons, the class class call to the GetName method of the array type will return a very strange name.

A virtual machine manages a class object for each type. You can use the = = operator to achieve the operation of two class object comparisons.

if (E.getclass () ==employee.class)

Newinstance () can be used to dynamically create an instance of a class (calling the default constructor).

E.getclass (). newinstance ();

Using Forname with newinstance, you can create an object based on the class name stored in the string.

Class.forName ("Java.util.Random"). newinstance ();

If you need to supply parameters to the constructor, you need to use the Newinstance method in the constructor class.

7.2 Catching exceptions

Throwing an exception is much more flexible than terminating the program because it can provide a "catch" exception to the processor to handle the exception condition.

There are two types of exceptions: The exception is not checked and the exception is checked. For checked exceptions, the compiler checks to see if the processor is available. For unchecked exceptions, the compiler does not look at the processor.

The simplest processor: place one or more method call code that might throw a checked exception in a try block, and then provide the processor code in the catch clause.

Throwable is a superclass of the exception class.

7.3 Ability to use reflection to analyze classes

The most important content of reflection mechanism--checking the structure of class

In the Java.lang.reflect package, there are three classes field, method, and constructor, which are used to describe the class's fields, methods, and constructors, respectively.

These three classes have a GetName method to return the name of the project, a getmodifiers method that returns an integer value, and a different bit switch to describe the use of modifiers such as public and static.

The field class has a GetType method that returns a description of the type to which the domain belongs.

The method and constructor classes have methods that can report parameter types.

The method class also has a way to report the return type.

The static method of the modifier class in the Java.lang.reflect package can also parse the integer value returned by the GetModifiers (IsPublic, isprivate, or isfinal). You can also print modifiers using the Modifier.tostring method.

The GetFields, GetMethods, and GetConstructors methods in the class class return the public domain, method, and constructor arrays that the classes provide, including the members of the superclass.

The Getdeclarefields, Getdeclaremethods, and Getdeclaredconstructors methods in the class class return all the fields, methods, and constructors declared in the classes, but do not include members of the superclass.

7.4 Using reflection to parse objects at run time

To view the data field name and type of any object:

1. Obtain the corresponding class object.

2. Calling getdeclarefields through the class object

The key method for viewing object fields is the Get method in the field class. If f is an object of Type field, and obj is an object of a class that contains an F field, F.get (obj) returns an object whose value is the current value of the domain with the same name as F in the Obj field.

Employee harry=New employee ("Harry hacker,35000,10,1,1989"); Class C1=harry.getclass (); Field F=c1.getdeclaredfield ("name"); Object v=f.get (Harry);

The default behavior of the reflection mechanism is limited by Java access control. You need to invoke the Setaccessible method of the field, method, or constructor object.

F.setaccessible (True)

Setaccessible is a method in the AccessibleObject class, which is a public superclass of the field, method, and constructor classes.

Of course, you can get it and set it up. Call F.set (Obj,value) to set the F field of the Obj object to the new value.

The following is a generic ToString method that can be used by any class.

ImportJava.lang.reflect.AccessibleObject;ImportJava.lang.reflect.Array;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Modifier;Importjava.util.ArrayList; Public classobjectanalyzer{PrivateArraylist<object> visited =NewArraylist<>(); /*** Converts an object to a string representation this lists all fields. * @paramobj an object *@returna string with the object's class name and all field names and * values*/    PublicString toString (Object obj) {if(obj = =NULL)return"NULL"; if(Visited.contains (obj))return"...";      Visited.add (obj); Class CL=Obj.getclass (); if(CL = = String.class)return(String) obj; if(Cl.isarray ()) {String R= Cl.getcomponenttype () + "[]{";  for(inti = 0; I < array.getlength (obj); i++)         {            if(i > 0) R + = ","; Object Val=array.get (obj, i); if(Cl.getcomponenttype (). Isprimitive ()) R + =Val; ElseR + =ToString (Val); }         returnR + "}"; } String R=Cl.getname (); //inspect The fields of this class and all superclasses       Do{R+= "["; Field[] Fields=Cl.getdeclaredfields (); Accessibleobject.setaccessible (Fields,true); //get the names and values of all fields          for(Field f:fields) {if(!modifier.isstatic (F.getmodifiers ())) {               if(!r.endswith ("[")) R + = ","; R+ = F.getname () + "="; Try{Class T=F.gettype (); Object Val=f.get (obj); if(T.isprimitive ()) R + =Val; ElseR + =ToString (Val); }               Catch(Exception e) {e.printstacktrace (); } }} r+= "]"; CL=Cl.getsuperclass (); }       while(CL! =NULL); returnR; }}

You can use the generic tostring method to implement the ToString method in your class (the domain in the entity class uses the base type) in the following ways:

 Public String ToString () {    returnnew Objectanalyzer (). ToString (this);}
7.5 Writing generic array codes using reflection

How do I construct a generic array?

Consider such a problem:

A employee[] array that is temporarily converted to object[] and then converted back is OK, but an array from the beginning is object[] can never be converted to a employee[] array.

Therefore, we need to be able to create a new array of the same type as the original array (some methods that need to java.lang.reflect the array class in the package, where the key is the static method newinstance in the array class, which can construct a new array)

Object newarray=array.newinstance (componenttype,newlength);

You need to provide two parameters when calling this method:

One is the length of the array--array.getlength (a)

One is the element type of the array--1. First get the class object of array A; 2. Confirm that it is an array; 3. Use the class class's Getcomponenttype method to determine the type of the array.

Here is a way to extend an array of any type:

 public  static  Object goodcopyof (  Object A, int   Newlength) {Class cl  = A.getclass ();  if  (!cl.isarray ()) return  null  ;      Class componenttype  = Cl.getcomponenttype ();       int  length = Array.getlength (a);      Object newarray  = Array.newinstance (ComponentType, newlength);      System.arraycopy (A,  0, NewArray, 0 return   NewArray; }

The reason why a parameter is declared here as an object type instead of a object[] type is that the integer array type int[] can be converted to an object and cannot be converted to an array of objects.

7.6 Calling any method

The reflection mechanism allows arbitrary methods to be called

A Get method similar to the field class looks at the object domain procedure, and there is an invoke method in the method class that allows you to invoke the method wrapped in the current method object.

Signature of the Invoke method:

Object Invoke (Object Obj,object ... args)

The first parameter is an implicit argument, the remaining parameter is a display parameter, and for a static method, the first parameter can be ignored, which is set to null.

For example: M1.invoke (Harry)--m1 is the GetName method for employee (non-static method)

F.invoke (null,6)--f is the Sqrt method of the math class (static method)

How to obtain the Method object:

Using the GetMethod method in class classes to get the desired method, similar to GetField (the GetField method returns a Field object based on the string representing the domain name), note that there may be several methods of the same name, You must also provide the parameter type of the method you want.

Signature of the GetMethod method:

Method GetMethod (String name,class ... parametertypes)

For example: Method m1=employee.class.getmethod ("Raisesalary", Double.class);

The code to get a method pointer using reflection is significantly slower than just calling the method directly, so it is advisable to use the method object only when necessary, preferably with an interface and a lambda expression.

In particular, we recommend that Java developers not use the callback function of the method object. Using an interface for callbacks can make your code execute faster and easier to maintain.

7.8 Inherited design Tips

1. Placing public operations and domains in a super class

2. Do not use protected domains

3. Implementing the "is-a" relationship with inheritance

4. Do not use inheritance unless all inherited methods make sense

5. Do not change the expected behavior when overriding the method

6. Using polymorphism, not type information

if (x is of type 1)

Action1 (x);

else if (x is of type 2)

Action2 (x);

Consider using polymorphism.

Code written using a polymorphic method or interface is more maintainable and extensible than using code that detects multiple types.

7. Do not use the reflection too much

Java Core technology-inheritance

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.