What inherits from class inheritance in Java?

Source: Internet
Author: User

The greatest benefit of inheritance is to implement code reuse. So what exactly does the subclass get from the parent class?

Instance members

Private members of the parent class do not inherit from the quilt class and cannot be accessed by subclasses. But the subclass object does contain a private member of the parent class. The package access member of the parent class inherits the package access member for the subclass. As if they were directly defined in the subclass. The protected member of the parent class is inherited as a protected member of the child class. As if they were directly defined in the subclass. The public members of the parent class are inherited as public members of the subclass, as if they were directly defined in the subclass.

Instance method

The inherited instance methods can be used directly in subclasses, and it is important to understand the overriding and overloading of methods.

overriding override

In an inheritance chain, the methods of the parent class have the same semantics for subclasses, but different details operate, so subclasses need to override this method of the parent class to meet their own needs.

Note the point:

1, the method name, the parameter table must be the same as in the parent class, the return type is the same, or the child class.

1, access rights must not be lower than the parent class instance method

2, throws the exception must be the parent class method throws the same exception, or subclass.

If you compare C + + with Java, the instance method in Java is virtual by default (there is no virtual key word in Java), so in Java, subclasses can directly override any non-final instance method of the parent class method, but in C + +, Subclasses can override this method unless the parent class uses virtual to mark a method as a virtual method.

For the overridden method, Javac is an indeterminate method for invoking that class, instead producing a special bytecode that allows the JVM to dynamically determine what method to make. This is the difference between the so-called early binding and late binding.

 Public class test{    publicstaticvoid  main (String [] args) {                new subclass ();                O.tostring ();    }} class  extends object{    public  String toString ()     //overriding Object The ToString Method    {        return "Subclass";    }}

Compiled from "Test.java" Public classTest { PublicTest (); Code:0: Aload_01:invokespecial #1//Method java/lang/object. " <init> ":() V4:return   Public Static voidMain (java.lang.string[]); Code:0:New#2//class Subclass3: DUP4:invokespecial #3//Method subclass. " <init> ":() V7: Astore_18: Aload_19:invokevirtual #4//Method java/lang/object.tostring: () ljava/lang/string;12: Pop13:return}

Of the 3 red labeled codes, the important difference is invokespecial and invokevirtual : invokespecial represents early binding, At compile time, you can decide what method to call, and Javac determines what method to call. Invokevirtual is the late binding of a method, and the JVM decides what method to invoke.

The first is that the constructor of the test class calls the constructor of the parent class object, and the compilation period determines that he is pre-bound.

The second is because new has a subclass object, calls the constructor of subclass, compiles the time to determine, he is also early bound.

The third is because our object o refers to the subclass object that overrides the ToString method, Javac does not know whether to call ToString in object, or ToString in subclass, and generates special code to let the JVM decide.

Methods that are modified to be static, final, private must be pre-bound because they do not exist at all.

The JVM needs to dynamically determine the method to invoke that version at run time, which is virtual lookup (virtual method lookup) for the JVM. The JVM will look from the class that the actual object belongs to and his nearest parent class . If you define it, call your own version, and if not, call the version of the parent class.

Heavy duty overload

Overloaded definitions: function overloading refers to a set of functions that have the same function name and different parameter lists within the same scope, which are called overloaded functions .

Note: overloading or not, the return type of the function is not considered. The same is true for C + +. That is, the return types of the 2 functions do not affect their ability to form overloads, as long as their function names are the same, and the parameter tables are different to satisfy the overloads.

Java is the default support for cross-class overloading. However, C + + does not support overloading an instance method of a parent class in a subclass by default. That is to say: instance methods in Java are automatically imported into the scope of the subclass, while C + + is not.

 Public classtest{ Public Static voidMain (string[] args) {Derive d=NewDerive (); D.print ("Hello", 2); D.print ("World");

/* Output
Hello
Hello
World
World
World
World
World

*/

}}classbase{ Public voidprint (String msg) { for(inti=0;i<5;++i) {System.out.println (msg); } }}classDeriveextendsbase{ Public voidPrint (String msg,intTimes ) //Overloading the parent class method in a subclass { for(inti=0;i<times;++i) {System.out.println (msg); } } }

For C + +

#include <iostream>#include<string>using namespacestd;classbase{ Public :        voidPrintConst string& msg)Const        {             for(intI=0;i<5;++i) {std::cout<<msg<<Std::endl; }        }};classDerive: Publicbase{ Public :        /** You need to use using Base::p rint The version in the parent class into the scope of the subclass to form a cross-class overload, otherwise the subclass will have the following compilation error when using a parameter version of the PRINT function: * * Erro         R:no matching function for call to ' Derive::p rint (const char [6]) ' * means that the compiler cannot find the version of print (const char [6]) in the Derive class * */        usingBase::p rint; voidPrintConst string& MSG,Const intTimesConst        {             for(intI=0; i<times;++i) {std::cout<<msg<<Std::endl; }        }};intMain () {Derive D; D.print ("Hello",2); D.print (" World");}
View Code

Instance fields

Instance fields there is nothing to say, but to say that the instance field is hidden: Define a field in the subclass with the same name as the parent class, and the name in the subclass hides the field in the parent class.

Few people use this technique, and if so, then there is a problem with the code design (bad code).

classbase{protected inti = 100;}classDeriveextendsbase{Private inti = 1000; //Hide the parent class field I  Public voidfoo () {System.out.println (i); //Representative This.iSystem.out.println ( This. i); System.out.println (Super. i);//using the parent class is hidden I            }    }

You can also use cast, which is the ultimate means. Because Super can only refer to members of the immediate parent class, it cannot refer to the parent class's members. But using cast can do it.

classa{protected inti = 100;}classBextendsa{protected inti = 1000;}classCextendsb{Private inti = 10000;  Public voidfoo () {System.out.println ("THIS.I:" + This. i);//10000System.out.println ("B.THIS.I:" + ((B) This). i);// +System.out.println ("A.THIS.I:" + ((A) This). i);// -    }}

Static member

Does static inherit from the quilt class? The answer is yes. They are inherited as static members of subclasses, not as members of child class instances.

Similarly, the private static member is not inherited, only the package access permission, and the protected public member is inherited.

Private members of the parent class do not inherit from the quilt class and cannot be accessed by subclasses. The package access member of the parent class inherits the package access member for the subclass. As if they were directly defined in the subclass. The protected member of the parent class is inherited as a protected member of the child class. As if they were directly defined in the subclass.  The public members of the parent class are inherited as public members of the subclass, as if they were directly defined in the subclass.

Static members can also use the access modifiers of instance members public, package access, protected, priavcte.

static method

The static method cannot be override and can only be hidden.

static field

As with instance fields, static fields can also be hidden. If you want to reference a hidden parent class static field, you need to explicitly use the class name of the parent class. Hiding static fields is often best not to use.

constructor function

Constructors cannot inherit, but subclasses must (and must) borrow the constructor of the parent class. Java Assurance: In addition to object class objects, each instance of a class is constructed, calling the constructor of the parent class first.

The first sentence of our custom class constructor must be super (xx,...), if not, then the first sentence must be this (xx,...) To call another constructor of this class.

If the subclass constructor does not explicitly call super (), then Javac will automatically insert super (), which is the constructor with no arguments to the parent class.

For constructors, all constructors in a class are implicitly static. The obvious example is that a constructor can be called without having to pass through an instance.

Welcome reprint, please specify Source: Www.cnblogs.com/lulipro

For a better reading experience, please visit the original blog address.

Limited to my level, if the article and code are not described in the wrong place, please do not hesitate to enlighten.

Code pianist

What inherits from class inheritance in Java?

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.