Java Learning Note (Core Java) 5 inheritance

Source: Internet
Author: User
Tags float double

Fifth Chapter Succession

1. Class Superclass sub-class
Inheritance: Extends (all inheritance sick a public inheritance, no private inheritance and protection inheritance)
c+++: By:

2. Using super (C # using base) to call the base class method
The subclass constructor defaults to calling the base class's parameterless construct to initialize the private domain of the base class
If the base class does not have a parameterless construct, an error will be

3.this:1. Referencing implicit arguments 2. Calling class other constructors
Super:1. Method of calling a superclass 2. Calling the constructor of a superclass

C + + uses the initialization list to invoke the constructor of the base class

4.java, you do not need to declare a method as a virtual method method, when the base-class pointer points to a different object, the virtual pointer knows the actual object type that the pointer is pointing to, so the corresponding method can be called correctly

If you do not want a method to have a virtual feature, you can mark it as final

5.java does not support multiple inheritance
6. Polymorphism: Dynamic binding, static binding, and Method table
1) The compiler knows exactly which method is called static binding
(method declared with private, static, final)
At run time, the calling method relies on the actual type and implements the method binding (known as runtime) called dynamic binding

Virtual machines generate a method table for base and derived classes, and a virtual opportunity to search the method table for the most appropriate method to invoke

The advantage of dynamic binding is that when you extend a program, you do not need to re-compile the code that calls the method

When a method is overridden, the method of a subclass cannot be accessed less than the base class method

7. Stop inheriting the final class
The final decorated class cannot be inherited
Final-modified methods cannot be overridden
Final-modified fields are initialized within the constructor method and cannot be altered

A class that is final decorated, whose method is automatically the final method, but does not include the domain

Dynamic binding is expensive for the system, so the instant compiler automatically marks non-overridden classes as inline functions, reducing overhead on the system

8. Casting
1) can only be converted within the inheritance hierarchy
2) After converting a base class to a subclass, you need to determine whether the conversion succeeded using the instanceof operator check
employee[] staff = new EMPLOYEE[3];
Java:manager boss = (Manager) staff[1];
if (staff[1] instanceof Manager)//instanceof instance belongs to this class
...
C + +: manager* boss= dynamic_cast<manager*> (staff[1])
if (boss!= null)
...

If the conversion fails, Java does not generate an empty object, but throws an exception

Add: C + + four coercion type conversions, so C + + is not type-safe
Static_cast: Basic Data type conversions
Const_cast: Constants are converted to extraordinary amounts, or vice versa
Reinterpret_cast: Any type conversion without consideration of security and constant issues, do not use it easily
dynamic_cast: Run-time conversion, run-time for type checking, between inheritance relationships (a virtual function in a class is required to perform this conversion, type information is checked, and type information is stored in the virtual function table)
9. Abstract classes and abstract methods
Abstract classes contain abstract methods that can also contain specific data, specific methods
Class does not immediately contain abstract methods, or can be declared as abstract classes
Abstract classes cannot be instantiated

C + +: The method of tail =0 is pure virtual function, the class containing virtual function is virtual class (abstract class) (virtual function can have its own implementation, pure virtual function =0)

10. Access Rights:
Private: This class is visible (it is also the reason for C + + initialization list, because the subclass is not a private field of the base class, it needs to call the constructor of the base class)

Public: Visible to all classes
Protected: This package and all subclasses are visible (C + + is only visible to sub-classes)
Default (no modifier): visible to this package

11.object Super Class
In Java, only the base type is not an object, and other types (including arrays, enumerations) are objects, all of which are extended to superclass

c++:void*, each pointer can be converted to a void* pointer

12.equal compares only if you have the same reference
It is best to manually override the Equal method

Overriding the requirements of the Equals method:
1. Reflexivity: x,x.equals (x) should return true for any non-null reference
2. Symmetry: For any reference to x and Y, if X.equals (y) returns True, then Y.equals (x) should also return true.
3. transitivity: For any reference to X, Y, and Z, if X.equals (y) returns True,y.equals (Z) returns True, then X.equals (z) should also return true.
4. Consistency: If the object referenced by x and Y does not change, repeated calls to X.equals (Y) should return the same result.
5. Non-nullability: x,x.equals (NULL) should return FALSE for any non-null reference.

Overriding the main points of the Equals method: (Note!) Override this method)
@overrade Public boolean equal (OBject otherobject)
1. Use the = = operator to check if the argument is the same reference to the object.
if (this = = Otherobject)
2. Determine if the argument is null
if (Otherobject = = null)
3. Use the instanceof operator to check if the argument is from the same class.
if (GetClass ()! = Otherobject.getclass ())//whether the same class
if (! ( Otherobject) instanceof ClassName)//If all subclasses have uniform semantics
4. Convert the arguments to the correct type.
ClassName other = (ClassName) otherobject

5. Compare all domains in turn: For each "critical" field in the class, check that the field in the argument matches the corresponding field value in the current object. For a field that is neither a float nor a double type, you can use the = = operator to compare, and for a field of the object reference type, the Equals method of the referenced object can be called recursively, and for a float-type domain, Use Float.floattointbits to convert to a value of type int, and then use the = = operator to compare values of type int, and for a field of type Double, use Double.doubletolongbits to convert to a long type, and then use = = The operator compares a long type value.

6. Once you have written the Equals method, you should ask yourself three questions: Is it symmetric, transitive, and consistent? (The other two features are usually self-fulfilling) if the answer is no, find the reason why these attributes are not satisfied, and then modify the code of the Equals method.

Arrays can use Arrays.equal to determine
////////////////////////////
Java.util.Arrays
Static Boolean equal (type[] a,type[] b);
Static Boolean equal (object A,object b);
////////////////////////////

13.hashCode
Each class has a hash code
If you rewrite equal, you also need to rewrite hashcode

14.toString strongly recommends that your class rewrite the string method for printing logs or error messages such as:
Public String toString ()
{
Return GetClass (). GetClass
+ "[name=" + Name
+ "age=" + Age
+ "]";
}

PRINTLN will call the X.tostring method directly

Array needs to call the Arrays.tostring method
Multidimensional Array Call arrays.deepstring method

/////////////////////////
Java.lang.Object
CALSS getclass ()//Returns the class object containing the object information
Boolean equal ()
String toString ();

Java.lang.Class
String GetName ();
Class Getsuperclass ()//Return superclass information
/////////////////////////

15. Generic array arraylist<t> array = new arraylist<t> ()
1) C + +: similar to vector, but not overloaded []. In C + +, the list a=b a value copy, whereas in Java, a=b A, B, points to the same list

(1) Add ()
Add (int index, T obj)//need to move a large number of elements
(2) ensurecapacity (100)//If the amount of storage can be estimated, a large internal//array space can be allocated before refilling
(3) Size = = Array A.length ()
(4) TrimToSize ()//If the confirmation list size no longer increases, you can call this method to clear the extra space

5) Set/get: Because there is no overloaded [] operator ....
Set (int IT obj);//Replace a value at a location (not incremented!) )
T get (int i); Returns an object that requires a cast after it gets
6) T Remove (int index)//need to move a large number of elements
7) x [] = new X[list.size ()]
List.toarray (x)//import Array
History Legacy Issues:
ArrayList List=employee.find (oldlist)//parameter list element may be somewhat inconsistent
Since the early ArrayList did not have generics, assigning a primitive ArrayList to a typed ArrayList would be a warning, as long as the @suppresswarning ("unchecked") could be used to close the warning.

16 Unpacking and Packing
Each base type has its corresponding class (Object wrapper Class)
Integer Long Float Double short Byte Character Void Boolean (first six inherited number classes)

The object wrapper class does not allow the modification of the value, but also the final declaration.
When a variable is declared with a wrapper, its = = indicates whether it points to the same object, so
Call the equal method when comparing two object wrappers

17.java How to change the value of the parameters??
C + +: pointer argument, reference to C #: Using ref notation to participate in formal parameters
Java Usage holder type (intholder, booleanhold, etc.)
public static void triple (IntHolder x)
{
X.value = 3 * x.value; Can change the value of a parameter
}

About C + + references:
A reference is actually a constant pointer, which is also implemented with a constant pointer. The reference occupies four bytes. Because it is a constant pointer, the contents of the referenced object cannot be modified. This is more secure than using pointers

/////////////////////////////
Java.lang.Integer
int intvalue ();//Returns the value in Interger
static string toString (int i);//wrap int as a decimal String
static String toString (int i,int radix);//Specify Binary
static int parseint (string s)//c# Int.prase (string s)
static int parseint (String s,int Radix)
Static Integer valueOf (String s)
Static Integer valueOf (String s,int Radix)

Java.text.Number.Format
Number Prase (String s); Suppose S is a numeric value
/////////////////////////////

18. Variable parameters use ...
public static double Max (double ... value);
Actually binds a number of parameters in the array to pass the Max function
public static void Main (String ... args);

19. Enumerate enum
is actually a class that contains several instances, so the values of the two enumerated types are compared, using = = directly, never calling equal.
All enum types are subclasses of the enum class. So they inherited many of the methods of this class string toString ()//Return enumeration constant name
static enum ValueOf (class enumclass,string name)//Returns the enumeration constant for the given class with the specified name
int ordinal ()//Returns the index of the enumerated constant in the enum declaration (starting at 0)
int CompareTo (E Other)//order comparison in enumerations

20 Reflection and reflection Library
Reflection is used extensively in JavaBeans.
The effect of reflection:
① ability to analyze classes in operation
② objects that are running in the view class
③ implementation of array manipulation codes
④ uses the method object. Special C + + image function pointers (C #, delegates and events)
Extremely powerful construction tools!!!

(1) Class
While the program is running, the Java runtime always maintains a type identity called Runtime for all objects, which keeps track of the classes each object belongs to, and the virtual opportunity uses the runtime's type information to choose the appropriate method to execute. The class is responsible for maintaining this information, and each Java class shows a class in the virtual machine type (which is easy to mix with instances of the GetClass return class in Object)

Employee e;
E.getname ();//Returns a class object

E.getclass (). GetName ();//Returns the name of the class

If the class is in the package, return the package name + instance Name
Data d = new data ();
Class C = D.getclass ();
String name = C.getname (); Java.util.Data

Use the static method forname to get the class object that corresponds to the name
String classname = "Java.util.Data";
Class C = forname (classname);//This method is only used in classname class name or interface name, otherwise it throws an exception checked exception. Use this method to provide an exception handler

(You can start the program first and then use forname to load all the classes, giving the user a quick-start illusion)

Use the T.class method to get a matching class object (t stands for any Java type)
Class C1 = Data.class
Class C2 = Int.class
Class C3 = double[].class//historical reason, the array will return a rather strange class name

Summarize:
Three ways to get class objects
The instance name. GetClass
Any type of T.class
Forname (class name string)//This is a static method Class.forName (s);

Class poin () {...}
Point P = new Point ();
Class C1 = P.getclaa ();
System.out.println (C1.getname ())//Point

Class C2 = class.forname ("point")
System.out.println (C2.getname ())//Point

Class C3 = Point.class;
System.out.println (C3.getname ())//Point

Each object in the class generates a Class object in the virtual machine to hold the information for each class, which can be obtained to obtain all the information about the class.
A virtual machine manages a class object for each type,
You can compare two classes of objects with = = (E.getclass () = = Employee.class) ...
You can also reflect the created object E.getclass () After you get the instance. newinstance ();
Newinstance () will tune the default construction method, and if not, throws an exception

Forname and Newinstance () Generate objects based on class name
String s = "Java.util,data";
Data D = (data) class.forname (s). newinstance ();

Newinstance ()//In the constructor class provides constructor parameters

////////////////////////////
Use Printstacktrace to print out the trajectory of the stack
Java.lang,class
Static Class forname (String classname);
Object newinstance ();

Java.lang,reflect. Constructon
Object newinstance (object[] args);//With parametric construction
////////////////////////////

Java Learning Note (Core Java) 5 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.