Subclass inherits the parent class, code execution order of presentation

Today saw a face questions:

father:

package test; 
public class FatherClass 
{ 
public FatherClass() 
{ 
System.out.println("FatherClass Create"); 
} 
} 

 

 

 

Subclass: 

package test; 
import test.FatherClass; 
public class ChildClass extends FatherClass 
{ 
public ChildClass() 
{ 
System.out.println("ChildClass Create"); 
} 
public static void main(String[] args) 
{ 
FatherClass fc = new FatherClass(); 
ChildClass cc = new ChildClass(); 
} 
} 

 

What Will the output is the result?

answer

FatherClass Create 
FatherClass Create 
ChildClass Create

 

This question is to examine the issue of sub-class inherits the parent class code execution order
First, create an object, we must call its constructor to initialize member functions and member variables. Sub-class has member variables and member methods of the parent class, so subclasses must call the parent class constructor, otherwise inherit from the parent class over the member variables and member methods are not properly initialized. Subclass object default constructor with no arguments to call the parent class in the creation of this call subclass does not have to be explicitly written out, but if the parent is not a class constructor with no arguments, it must be the first in the constructor subclass of call the parent class has a constructor parameter, and make the parameters passed to the constructor of the superclass.

Such as:

father:

public class Father 
{ 

public Father(int i) 
{ 
System.out.println("有参数的:FatherClass Create"); 
} 


} 

 

* Parent class constructor with no arguments is not provided

 

Subclass:

public  class Child the extends Father 
{      
public Child () 
{ 
    Super (. 5); // this is the first line constructor must subclass, or the compiler error 
System.out.println ( "the ChildClass the Create" ); 
} 
public  static  void main (String [] args) 
{ 
Father FC = new new Father (2 ); 
Child CC = new new Child (); 

} 
}

 

At this output:

There are arguments: FatherClass Create 
with arguments: FatherClass Create 
ChildClass the Create

 

Guess you like

Origin www.cnblogs.com/newbie273/p/11728339.html