Inheritance - Constructor Overridden - X++ Code
Table of Content:
New method - Creates an instance of the class by using the new
keyword. The default constructor is new(). The following is an example of declaring a variable and creating an instance of an object by calling the new method:
Syntax
Sample mySample; //this declares a variable to refer to a sample object mySample = new Sample(); //this creates an instance of a sample object
Inheritance - Constructor Overridden - X++ Code
In this section you will learn how to override constructor in x++ programming language. We override constructor is to initialize values in parent class.
Parent Class
class VehicleClass{ // Instance fields. real height; real width; // Constructor to initialize fields height and width. void new(real _height, real _width) { height = _height; width = _width; } void run(){ info("Running"); } }
Child Class
class CarClass extends VehicleClass{ // Additional instance field numberOfPassengers. Fields height and width are inherited. int numberOfPassengers; // Constructor is overridden to initialize. void new(real _height, real _width, int _numberOfPassengers) { // Initialize the fields. super(_height, _width); numberOfPassengers = _numberOfPassengers; } public static void main(Args arg) { CarClass obj = new CarClass(12.0, 12.0, 3); obj.run(); info(strFmt("Height %1", obj.height)); info(strFmt("Width %1", obj.width)); info(strFmt("number Of Passengers %1", obj.numberOfPassengers)); } }
Output
number Of Passengers 3 Width 12.00 Height 12.00 Running