Java Learning Notes (13): Procedures for subclass initialization __java

Source: Internet
Author: User

Subclass inherits the parent class, when you create the subclass object, you call the parent class's constructor, and then call your own constructor, if a method is called in the constructor of the parent class, and the method quilt is overridden, then the overridden method of the subclass is invoked.

Example:

Package constructor;

Class A
{
	a ()
	{
		draw ();
		System.out.println ("A is constructing");
		
	}
	void Draw ()
	{
		System.out.println ("A is drawing!");
	}
public class B extends A
{
	private int m = 1;
	B (int m)
	{
		this.m = m;
		System.out.println ("B is constructing! m = "+integer.tostring (m));
	}
	void Draw ()
	{
		System.out.println ("B is drawing! m = "+integer.tostring (m));
	}
	public static void Main (string[] args)
	{
		new B;
		The output is as follows/
		*
		b is drawing! m = 0
		A are constructing B is
		constructing! m = Ten 
		 */
	}
}
As shown above:

You will find that the value of M should be 1 for the first time, but output 0, because the object's storage space is initialized to binary 0 when the object is constructed.

When you create a subclass object B, the actual process of initialization is as follows

(1) The storage space allocated to the object is initialized to the binary 0 before any other thing occurs

(2) Call the constructor of the parent class, call the corresponding method draw, because (1), cause m = 0

(3) Initialized by class member, at this time M = 1

(4) Calling the constructor of the subclass

Therefore, in general, the final method or Private method is called in the constructor (the private method automatically belongs to the final method), so that the class does not overwrite the final methods of the parent class, so that the overridden method of the subclass cannot be invoked when the parent class constructor is invoked, thus avoiding the M = 0 situation, because this will not invoke the draw method of the subclass


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.