|
Also see method overloading
Link |
Overloading constructor use of overloaded methods :
- in the same class or a subclass
- the method in the derived class, would have the same method name
used in a base class
- the method in the derived class, would have the same name, but would
have different parameter lists
|
import java.util.*;
import java.io.*;
//javac clas_name.java
public class test
{
private static int player_no = 12;
public test()
{ System.out.println("This is a constructor with no param");
}
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Type something : ");
String str = "";
str = br.readLine();
method_client dc = new method_client();
method_client mc = new method_client(str);
mc.method_1();
}
}
class method_server
{
private int n1 = 12;
public method_server() { System.out.println("\tserver constructor"); }
public void method_1(int n1)
{
System.out.println("\tmethod server : " );
System.out.println("\tPrint server variable n1 : " + this.n1);
this.n1 = n1;
System.out.println("\tPrint server variable n1 : " + this.n1);
}
}
class method_client extends method_server
{
private int n1 = 24;
String str;
public method_client(){ System.out.println("client default constructor");}
public method_client(String str){ System.out.println("client overloaing
constructor");
this.str = str;}
public void method_1()
{
System.out.println("client : " + str);
System.out.println("Print client variable : " + n1);
//late binding a method/class from main; the this method is hidden to the
caller.
this.method_1(n1);
}
}
|
 |
Command Line code |
import java.util.*;
import java.io.*;
//javac overload_constructor.java
public class overload_constructor
{
private static int player_no = 12;
public overload_constructor()
{ System.out.println("This is a constructor with no param");
}
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Type something : ");
String str = "";
str = br.readLine();
method_client dc = new method_client();
method_client mc = new method_client(str);
mc.method_1();
}
}
class method_server
{
private int n1 = 12;
public method_server() { System.out.println("\tserver constructor"); }
public void method_1(int n1)
{
System.out.println("\tmethod server : " );
System.out.println("\tPrint server variable n1 : " + this.n1);
this.n1 = n1;
System.out.println("\tPrint server variable n1 : " + this.n1);
}
}
class method_client extends method_server
{
private int n1 = 24;
String str;
public method_client(){ System.out.println("client default constructor");}
public method_client(String str){ System.out.println("client overloaing
constructor");
this.str = str;}
public void method_1()
{
System.out.println("client : " + str);
System.out.println("Print client variable : " + n1);
this.method_1(n1);
}
}
|
 |