B4J Question Overloaded Constructor in B4J Class Module

Johan Schoeman

Expert
Licensed User
Longtime User
I have browsed the forum but could not find a solution for the below (i.e a class with overloaded constructors). a B4J class does require the default Initialize method (can modify to pass parameters) but how would one go about to allow for all 3 the constructors in a B4J class as per java code below?

B4X:
public class V2D {

    private double x;
    private double y;
    private double norm;
    
    
    // ------------
    // constructors
    // ------------
    
    public V2D() {
        this.x = 0.0;
        this.y = 0.0;
    }

    public V2D(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public V2D(V2D p) {
        this.x = p.getX();
        this.y = p.getY();
    }
 

Daestrum

Expert
Licensed User
Longtime User
seems to work
The class file
B4X:
Sub Class_Globals
    Private x As Double
    Private y As Double
    Private norm As Double
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize (obj() As Object)

    If obj = Null Then
        x = 0
        y = 0
        norm = 0
    else if obj.Length = 1  Then
        x = obj(0).As(MyClass).x
        y = obj(0).As(MyClass).y
    else if obj.Length = 2 Then
        x = obj(0).As(Double)
        y = obj(1).As(Double)
    End If
End Sub

Sub setX(xv As Double)
    x = xv
End Sub

Sub setY(yv As Double)
    y = yv
End Sub

Sub getX As Double
    Return x
End Sub

Sub getY As Double
    Return y
End Sub

The caller
B4X:
Sub Process_Globals
    Dim mm, mm1, mm2 As MyClass
End Sub

Sub AppStart (Args() As String)
    mm.Initialize(Null)
    Log("mm = " & mm)
    mm1.Initialize(Array(5.0, 10.0))
    Log("mm1 = " & mm1)
    mm2.Initialize(Array(mm1))
    Log("mm2 = " & mm2)
End Sub
 
Upvote 0
Top