first, Create a transport class, define the properties and methods of the class, and write a good construction method, first look at the constructor without parameters:
public class Transport { // name public String name; // type of transport public String type; public void Todo () { System.out.println ("vehicles can be manned"); } public Transport () { System.out.println ("no parameter constructed method executed")} }
Then instantiate the transport class:
public Static void main (string[] Args) { new// Output parameterless construction method executed }
And then look at the constructor with the Parameters:
public Transport (string myName, string MyType) { = myName; = myType; System.out.println ("constructor method with parameters executed, parameter:" +name+ "," +type "); }
Instantiate the Output:
public Static void main (string[] Args) { new// Parametric construction method executed, parameters: airplane, Air }
If the parent class is a constructor with parameters, the subclass must also use the constructor with parameters as the parent class and use the Super () method to invoke the parent Class's constructor, which inherits the parent class and invokes the parent class properties and Methods:
public class extends Transport {publicvoid todo () { System.out.println (name+ "is The fastest means of transport" ); } public Plane (string myName, string MyType) { Super(myname,mytype); } publicvoid test () { Super. Todo (); }}
Instantiate the Output:
public Static void main (string[] Args) { new Plane ("aircraft", "airlift"); Here is the super (myname,mytype), the output parameters of the construction method executed, parameters: aircraft, Air Plane.todo ();//aircraft is the fastest means of transport Plane.test (); Vehicles can be manned by the load}// output result is:
The constructor method with parameters is executed, parameters: aircraft, air
Subclass Instantiation Parameters: Air 300
Airplanes are the quickest means of transport.
Vehicles can carry a manned load
In summary, if a subclass has its own constructor, its arguments cannot be less than the parameters of the parent class, but it is possible to add the Subclass's own new constructor parameters, such as:
public int speed ) { Super(myname,mytype); System.out.println ("subclass instantiation parameter:" +myname+mytype+ speed); }
New Plane ("aircraft", "air freight", +); parameter construction method executed, parameters: aircraft, Airlift sub-class instantiation parameters: Air freight
How to construct in Java