package initialization;//: initialization/SimpleConstructor.java// Demonstration of a simple constructor.classRock{Rock(){// This is the constructor
System.out.print("Rock ");}}publicclassSimpleConstructor{publicstaticvoidmain(String[] args){for(int i =0; i <10; i++)newRock();}}/* Output:
Rock Rock Rock Rock Rock Rock Rock Rock Rock Rock
*///:~
ExerciseCode_02
package initialization;//: initialization/SimpleConstructor2.java// Constructors can have arguments.classRock2{Rock2(int i){
System.out.print("Rock "+ i +" ");}}publicclassSimpleConstructor2{publicstaticvoidmain(String[] args){for(int i =0; i <8; i++)newRock2(i);}}/* Output:
Rock 0 Rock 1 Rock 2 Rock 3 Rock 4 Rock 5 Rock 6 Rock 7
*///:~
ExerciseCode_03
package initialization;//: initialization/Overloading.java// Demonstration of both constructor and ordinary method overloading //构造函数和普通方法重载的演示importstatic net.mindview.util.Print.*;classTree{int height;Tree(){print("Planting a seedling");
height =0;}Tree(int initialHeight){
height = initialHeight;print("Creating new Tree that is "+ height +" feet tall");}voidinfo(){print("Tree is "+ height +" feet tall");}voidinfo(String s){print(s +": Tree is "+ height +" feet tall");}}publicclassOverloading{publicstaticvoidmain(String[] args){for(int i =0; i <5; i++){
Tree t =newTree(i);
t.info();
t.info("overloaded method");}// Overloaded constructor:newTree();}}/* Output:
Creating new Tree that is 0 feet tall
Tree is 0 feet tall
overloaded method: Tree is 0 feet tall
Creating new Tree that is 1 feet tall
Tree is 1 feet tall
overloaded method: Tree is 1 feet tall
Creating new Tree that is 2 feet tall
Tree is 2 feet tall
overloaded method: Tree is 2 feet tall
Creating new Tree that is 3 feet tall
Tree is 3 feet tall
overloaded method: Tree is 3 feet tall
Creating new Tree that is 4 feet tall
Tree is 4 feet tall
overloaded method: Tree is 4 feet tall
Planting a seedling
*///:~
ExerciseCode_04
package initialization;//: initialization/OverloadingOrder.java// Overloading based on the order of the arguments. // 基于参数顺序重载importstatic net.mindview.util.Print.*;publicclassOverloadingOrder{staticvoidf(String s,int i){print("String: "+ s +", int: "+ i);}staticvoidf(int i, String s){print("int: "+ i +", String: "+ s);}publicstaticvoidmain(String[] args){f("String first",11);f(99,"Int first");}}/* Output:
String: String first, int: 11
int: 99, String: Int first
*///:~