Class and Inheritance (i)

Source: Internet
Author: User
Tags export class

In Java, Class files are code files that are suffixed with. Java, and only one public class is allowed in each class file, and when there is a public class, the name of the class file must be the same as the name of the public class, and if there is no public, the name of the class file can be any name (which is not allowed, of course).

Within a class, for member variables, Java guarantees that every member variable of a class is properly initialized if it is not initialized with a display at the time it is defined:

1) For variables of basic data types such as char, short, byte, int, long, float, double, are initialized to 0 by default (the Boolean variable is initialized to False by default);

2) for a variable of a reference type, it is initialized to null by default.

If the constructor is not displayed, the compiler automatically creates a parameterless constructor, but keep in mind that the compiler does not automatically add the constructor if the constructor is defined in the display. Note that all constructors default to static.

Let's focus on the initialization sequence:

When the program executes, the object of a class needs to be generated, and the Java execution Engine first checks whether the class is loaded, and if it does not, executes the class's load before generating the object, and if it is already loaded, generates the object directly.

Static member variables of a class are initialized during the load of the class, and static statement blocks are executed if there are static statement blocks in the class. Static member variables and static statement blocks are executed in the same order as in the code. Remember, in Java, the class is loaded on demand, and it is only loaded once when the class needs to be used. Let's see the following example:

public class Test {public static void main (string[] args) throws ClassNotFoundException {Bread bread1 = new Bread (); Bread bread2 = new Bread ();}} Class Bread {static{system.out.println ("Bread is Loaded");} Public Bread () {System.out.println ("Bread");}}

Running this code will find that "Bread is loaded" will only be printed once.

In the process of building an object, the member variables of the object are initialized before the constructor is executed. This means that the variables in the class are initialized before any methods (including constructors) are called, even if the variables are strolling between the method definitions.

public class Test {public static void main (string[] args)  {new Meal ();}} Class Meal {public Meal () {System.out.println ("Meal");} Bread Bread = new Bread ();} Class Bread {public Bread () {System.out.println ("Bread");}}

The output is:

Breadmeal
Two. Do you understand inheritance?

Inheritance is an integral part of all OOP languages, and the extends keyword is used in Java to represent an inheritance relationship. When a class is created, it is always inherited, and it is always implicitly inherited from the root class object if it is not explicitly pointed out to inherit the class. For example, the following code:

Class Person {public ' () {}}class man extends ()}

The class man inherits from the person class, so that the person class is called the parent class (the base class), and the man class is called a subclass (export Class). If an inheritance relationship exists for two classes, the subclass automatically inherits the methods and variables of the parent class, and the methods and variables of the parent class can be called in the subclass. In Java, only single inheritance is allowed, that is, a class can only be displayed to inherit from a parent class at most. But a class can be inherited by multiple classes, which means that a class can have more than one subclass.

1. Subclass inherits member variables of parent class

When a subclass inherits a class, the member variables in the parent class can be used, but not all member variables of the parent class are fully inherited. The specific principles are as follows:

1) The ability to inherit the public and protected member variables of the parent class, and the private member variables of the parent class cannot be inherited;

2) for the package access member variable of the parent class, the subclass can inherit if the child class and parent class are under the same package, otherwise the subclass cannot inherit;

3) for the parent class member variable that the subclass can inherit, if a member variable of the same name appears in the subclass, a shadowing occurs, that is, the member variable of the child class masks the member variable with the same name as the parent class. If you want to access a member variable of the same name in the parent class in a subclass, you need to use the Super keyword to refer to it.

2. Subclasses inherit methods of parent class

Similarly, subclasses do not fully inherit all the methods of the parent class.

1) The ability to inherit the public and protected member methods of the parent class, and the private member method of the parent class cannot be inherited;

2) for the parent class of the package access member method, if the child class and the parent class under the same package, the subclass can inherit, otherwise, the subclass can not inherit;

3) for the parent class member method that the subclass can inherit, if a member method of the same name appears in the subclass, then it is called overwrite, that is, the member method of the subclass overrides the member method with the same name as the parent class. If you want to access a member method of the same name in the parent class in a subclass, you need to use the Super keyword to refer to it.

Note: Hiding and overwriting are different. Shadowing is for member variables and static methods, and overrides are for common methods. (I'll talk about it later)

3. Constructors

Subclasses are constructors that cannot inherit the parent class, but note that if the constructor of the parent class is parameterized, the constructor of the parent class must be called with the Super keyword in the constructor of the child class and be accompanied by the appropriate argument list. If the parent class has a parameterless constructor, it is not necessary to call the parent class constructor with the Super keyword in the subclass's constructor, and if the Super keyword is not used, the system automatically calls the parent class's parameterless constructor. See the following example to make it clear:

Class Shape {protected String name;public shape () {name = "shape";} Public Shape (String name) {this.name = name;}} Class Circle extends Shape {private double radius;public Circle () {radius = 0;} Public Circle (double radius) {This.radius = radius;} Public Circle (double radius,string name) {This.radius = Radius;this.name = name;}}

There is no problem with this code, and if you remove the parameterless constructor of the parent class, the following code will inevitably go wrong:

Change it to the following line:

4.super

There are two main uses of super:

1) Super. Member variable/super. Member method;

2) Super (Parameter1,parameter2 ...)

The first is used to invoke the parent class's member variable or method in the subclass, and the second is to call the constructor of the parent class in the constructor of the subclass, and note that if it is used in the subclass constructor, it must be the first statement of the child class constructor.

Three. Common Interview Pen Questions

1. What is the output of the following code?

public class Test {public static void main (string[] args)  
Shape Draw Constructorshape Constructorcircle draw Constructorcircle Constructor

This topic focuses on the sequence of calls and initialization of constructors at class inheritance. One point to remember is that the constructor invocation of the parent class and the initialization process must precede the child class. Because the Circle class's parent class is a shape class, the Shape class initializes first and then executes the constructor of the shape class. Then the sub-class circle is initialized, and the last circle's constructor is executed.

2. What is the output of the following code?

public class Test {public static void main (string[] args)  {shape shape = new Circle (); System.out.println (Shape.name); Shape.printtype (); Shape.printname ();}} Class Shape {public String name = "Shape";p ublic shape () {System.out.println ("shape constructor");} public void Printtype () {System.out.println ("This is Shape"); public static void Printname () {System.out.println ("shape");}} Class Circle extends Shape {public String name = "Circle";p ublic Circle () {System.out.println ("circle constructor");} public void Printtype () {System.out.println ("This is Circle"); public static void Printname () {System.out.println ("Circle");}}
Shape Constructorcircle Constructorshapethis is CircleShape

This topic examines the difference between hiding and covering (and, of course, polymorphism, which will continue in subsequent posts).

Overrides are only for non-static methods (the end-state method cannot be inherited, so there is a overwrite), and the shadowing is for member variables and static methods. The difference between the 2 is that the overlay is constrained by the RTTI (Runtime type identification) and is hidden from the constraint. This means that only the overlay method will be dynamically bound, and the shadowing will not occur dynamically. In Java, all other methods, except the static method and the final method, are dynamically bound. As a result, the above output will appear.

Class and Inheritance (i)

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.