Java and talk about inheritance super class Object

Come talk to inheritance, as well as super class Object.

01, first inheritance, after how state

Use inheritance, we can construct a new class based on an existing class. The benefits of inheritance is that a subclass can be reused non-parent class privatemethod and the non- privatemember variables.

is-aInheritance is a distinctive feature of the object that is referenced subclass may be a parent type. We apply the common member variables and methods in the parent class, the purpose of the reuse of code; then, special methods and member variables in a subclass, in addition, the parent class further subclass may be covered . In this way, a subclass also brought out a new vitality.

A plurality of types can be referenced object variable phenomenon is called polymorphism. Prerequisites polymorphic happen is inherited. In other words, first inheritance, after how states.

class Wanger {

    public void write() {
        System.out.println("我为自己活着");
    }

}

class Wangxiaoer extends Wanger {
    public void write() {
        System.out.println("我也为自己活着");
    }
}

class Test {
    public static void main(String [] args) {
        Wanger wanger;
        wanger = new Wanger();
        wanger = new Wangxiaoer();

        Wangxiaoer wangxiaoer;
        //wangxiaoer = new Wanger(); // 不可以
        wangxiaoer = new Wangxiaoer(); // 只能这样
    }
}

wangerThe object variable can refer to both Wangerobjects can reference Wangxiaoerobjects. But wangxiaoeryou can only refer to Wangxiaoeran object, not a reference Wangerobject. The fundamental reason is that Wangxiaoera Wangersuccessor.

When wangerinvoked write()when methods, the program will automatically identify the type of object it references at runtime, and then choose which method to call - a phenomenon known as dynamic binding.

Dynamic binding has a very important feature: no need to modify existing code, it can extend the program. If you Wangdaerhave inherited Wanger, and wangercited the Wangdaerobject, then wanger.write()it can still operate normally.

Of course, some classes do not want to be inherited, and can not be inherited. Who does not want to be inherited? For example, Wu, personally kill his own son. Who can not be inherited it, each toward each generation of hapless last emperor.

Like how you do not inherit it? You can use finalkeywords. finalKeyword modified class can not be inherited, finalmodified method can not be overridden.

final class Wanger {

    public final void write() {
        System.out.println("你们谁都别想继承我");
    }

}

Inheritance is among the important object-oriented programming concept, polymorphic, co-encapsulation of object-oriented three basic characteristics. Inheritance can be made with the subclass member variables and methods of the parent class can also redefine an additional member variables and methods.

In the design inherited when common methods and member variables can be placed in the parent class. But not arbitrarily recommend the member variables in protectedthe form in which the parent class; although allowed to do so, and the subclass can be directly accessed when needed, but this will destroy the encapsulation class (encapsulation member variables required in privatethe form of It occurs, and to provide a corresponding getter / setterused to access).

Java is not allowed more than inheritance , and why?

If there are two classes of common inherited from the parent class of a particular method, the method is overridden two sub-categories. Then, if you decide to inherit the two sub-categories, so when you call the override method, the compiler can not identify which sub-class method you want to call.

This is exactly the famous diamond issue, see below. ClassC inherits the ClassA and ClassB, ClassC object when calling methods and ClassA ClassB in overloaded, do not know the method call ClassA method, or the ClassB.

Java and talk about inheritance super class Object

02, super class Object

In Java, all classes inherited by the Object class. Object of this word in English means that the object is not a sudden epiphany - Everything Is an Object? Yes, Java designers really care and thought, ah! Now, you must understand the reasons why Java is an object-oriented programming language.

You may be puzzled to ask: "I obviously did not inherit class Object class ah?" If a class is useless explicitly inherit a certain class, it will implicitly inherit the Object class. In other words, whether it is a raw chicken egg, chicken or the egg hatched, there is always an Object or an Object chicken egg.

In the interview, you may be asked such a question: "Object class contains a way to do what?"

1) protected Object clone() throws CloneNotSupportedExceptionCreates and returns a copy of this object.

However, "Ali Baba Java Development Manual" recommendations: caution Object clone method to copy objects. Because the clone method of Object default shallow copy, if you want to achieve a deep copy need to override clone method to achieve copy the object's properties.

What is shallow copy, what is a deep copy of it?

Shallow copy means copying an object, the basic data types of variables will have to re-copy, and for a reference type variable is only a reference copy and no object reference points to be copied.

Deep copy means copying the object, while the object reference points to be copied.

Shallow vs. deep copy difference lies in whether the object is copied object reference variable points.

2) public boolean equals(Object obj)to determine whether this object and other objects "equal."

This method uses the highest degree of differentiation "==" operator judgment, so long as the two objects are not the same object, then the equals()method must return false.

It stressed the "Ali Baba Java Development Manual": As the equals method of Object is easy to null pointer exception is thrown, so it should be determined using constant or not null object to call the equals.

Positive examples: "test".equals(object);
counterexample:object.equals("test");

In the formal development projects, the most frequently used method is to judge the string. However, it is recommended to use org.apache.commons.lang3.StringUtils, do not worry about null pointer exception. Specific use is as follows:

StringUtils.equals(null, null)   = true
StringUtils.equals(null, "abc")  = false
StringUtils.equals("abc", null)  = false
StringUtils.equals("abc", "abc") = true
StringUtils.equals("abc", "ABC") = false

3) public native int hashCode()Returns the hash code for this object. hashCode()Is a nativemethod, and the return line is an integer value type; in fact, the method the object address in the memory as a hash code is returned, the return value may be different to ensure that different objects.

A native method is a Java method whose implementation is provided by non-java code. <br>
nativemethod is a Javanon-call Javacode interface. The method implemented by the non- Javaimplementation language, such as C. This feature is not Javaunique, other programming languages also have this mechanism, for example C++.

hashCode()Usually play a role in the hash table, for example HashMap.

Was added to the hash table Object, the first call the hashCode()method of calculating the Objecthash code, a hash code may be positioned directly by Objectthe position in the hash table. If this is not the object position, can be directly Objectinserted position; if the Location object, invoke equals()methods compare object Objectis equal, if equal, there is no need to save Object; if not equal, then this Objectwas added to the hash table .

4) protected void finalize() throws ThrowableWhen the garbage collection mechanism determines that the object is no longer invoked, the garbage collector will call this method. However, the fnalizemechanism is now not recommended, and in JDK 9 began to be marked deprecated(obsolete).

5) public final Class getClass()Returns the runtime class of this object.

When we want to know some information (for example, class name) a class of their own, how to do it? This time we need to use Classclass, which contains information about the class. Consider the following code:

Wanger wanger = new Wanger();
Class c1 = wanger.getClass();
System.out.println(c1.getName());
// 输出 Wanger

6) public String toString()Returns a string representation of the object.

"Ali Baba Java Development Manual" compulsory: POJO class must override the toStringmethod; can be used to directly generate Eclipse, click on the "Source" → "Generate toString." Examples are as follows:

class Wanger {
    private Integer age;

    @Override
    public String toString() {
        return "Wanger [age=" + age + "]";
    }

}

Rewrite toString()what good is it? When the method throws an exception during execution may be invoked directly POJO toString()method of printing attribute values, easy to troubleshoot.

POJO (Plain Ordinary Java Object) refers to simple Java objects, which is common JavaBeans, and contains a number of member variables getter / setter, no business logic. Sometimes called VO (value - object), sometimes called DAO (Data Transform Object).

03, summary

Manual carefully before we talk about the important features of object-oriented inheritance; then talked about the succession of the ultimate parent Object. Knowledge of these points are very important, be sure to deeply understand!

Previous: please use object-oriented thinking, talk about the interview process

Next: the Java: interfaces and abstract classes, silly you could not tell?

Thank you for reading, originality is not easy, like they readily point a praise

Guess you like

Origin blog.51cto.com/2324584/2450265