- Home /
Calling inherited constructor
Is it possible to call the inherited Constructor from a Subclasses Constructor?
This DOES work, but, note I had to create a helper function called constructBase() which seems round about:
public class Base { public var num : int = 5;
function Base() {}
function Base(num : int) {
this.constructBase(num);
}
function constructBase(num : int) {
this.num = num;
}
}
public class Sub extends Base { function Sub(num : int) { super.constructBase(num); } function print() { Debug.Log(this.num); } }
This is more along the lines of what I'd expect to be able to do, but this doesn't work, it will print 5 when creating an instance of the subclass.
public class Base { public var num : int = 5;
function Base() {}
function Base(num : int) {
this.num = num;
}
function constructBase(num : int) {
this.num = num;
}
}
public class Sub extends Base { function Sub(num : int) { Base(num); } function print() { Debug.Log(this.num); } }
I know in C# you can call a base construct as shown in the link without much trouble, but I don't know if or how the syntax carries over to js.
Answer by DaveA · Mar 12, 2012 at 11:12 PM
Did you try
super(num); // where 'super' is a reserved word
Answer by monkeyThunk · Mar 12, 2012 at 10:06 PM
Sorry, a little more readable:
Does work:
public class Base { public var num : int = 5;
function Base() {}
function Base(num : int) {
this.constructBase(num);
}
function constructBase(num : int) {
this.num = num;
}
}
public class Sub extends Base {
function Sub(num : int) {
super.constructBase(num);
}
function print() {
Debug.Log(this.num);
}
}
Does NOT work:
public class Base {
public var num : int = 5;
function Base() {}
function Base(num : int) {
this.num = num;
}
function constructBase(num : int) {
this.num = num;
}
}
public class Sub extends Base {
function Sub(num : int) {
Base(num);
}
function print() {
Debug.Log(this.num);
}
}
Answer by monkeyThunk · Mar 12, 2012 at 11:26 PM
Hey that works, thanks!
Is Unity Javascript in fact JScript ? That would be really useful to know!
Your answer
Follow this Question
Related Questions
Referencing the object that a construtor is currently constructing/working on. 1 Answer
Construct class with enum parameter (javascript) 0 Answers
Recognizing a Mouse Click between Scripts 1 Answer
How can I give a description to a constructor for a custom class? 2 Answers
Array of custom class objects all return the same value? 1 Answer