Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
Line 318:
 
<syntaxhighlight lang="java">
class ExampleX {
public ExampleX() { // Non-parameterized constructor
this(1); // Calling of constructor
System.out.println("0-arg-cons");
}
 
public ExampleX(int a) { // Parameterized constructor
System.out.println("1-arg-cons");
}
}
 
public static void main(String[] args)
public class Example {
{
public static void main(String[] args) {
Example e = new Example();
X x = new X();
}
}
</syntaxhighlight>
Line 337 ⟶ 339:
 
<syntaxhighlight lang="java">
public class ExampleX {
// Declaration of instance variable(s).
private int data;
 
// Definition of the constructor.
public ExampleX() {
this(1);
}
 
// Overloading a constructor
public ExampleX(int input) {
data = input; // This is an assignment
}
}
</syntaxhighlight>
 
class Y extends X {
<syntaxhighlight lang="java">
private int data2;
// Code somewhere else
 
// Instantiating an object with the above constructor
public Y() {
Example e = new Example(42);
super();
data2 = 1;
}
 
public Y(int input1, int input2) {
super(input1);
data2 = input2
}
}
 
public class Example {
public static void main(String[] args) {
Y y = new Y(42, 43);
}
}
</syntaxhighlight>