关于构造,程序语言中数据初始化是个极其重要的问题,Java也不例外,由此产生了构造的概念,
The name of the constructor is the same as the name of the class,it maks sense that such a method will be called automatically during initialization.
class Rock {
Rock() {
System.out.print("Rock ");
}
}
public class SimpleConstructor {
public static void main(String[] args) {
for(int i=0;i<3;i++)
new Rock();
}
}
从这一点上来说,构造可以看作特殊的方法,方法名特殊,无返回值,
很崩溃,第一道练习就出错…….
public class Exer1 {
public Exer1(String s) {
System.out.println(s);
}
public static void main(String[] args) {
new Exer1(s);
}
}
class Tester {
String s;
}
public class ConstructorTest {
public static void main(String[] args) {
Tester t = new Tester();
System.out.println(t.s);
}
}
原来是这么做的,看来每道题都需要动手做阿,做了才会发现问题
class Tester2 {
String s1;
String s2 = "hello";
String s3;
Tester2() { s3 = "good-bye"; } // it is easy to see that there is no difference between contructor method and fields setting.
}
public class Test2 {
public static void main(String[] args) {
Tester2 t = new Tester2();
System.out.println("t.s1: " + t.s1);
System.out.println("t.s2: " + t.s2);
System.out.println("t.s3: " + t.s3);
}
}
Method overloading
Wash the skirt,wash the car,wash the dog,and it would be silly to be forced to say “skirtWash skirt,carWash car …’’
Method overloading is essential to allow the same method name to be used with different argument types.
The this keyword is used only for those special cases in which you need to explicitly use the reference to the current object.E.g,it’s often used in return statements when you want to return the reference to the current object.
public class Leaf {
int i=0;
Leaf increment() {
i++;
return this; //here cant be any other variables,and the this is very suitable
}
void print() {
System.out.println("i= "+i);
}
public static void main(String[] args) {
Leaf x=new Leaf();
x.increment().increment().increment().print();
}
}
This was ued to pass the object
class Person {
public void eat(Apple apple) {
Apple peeled=apple.getPeeled();
System.out.println("Yummy");
}
}
class Peeler {
static Apple peel(Apple apple) {
return apple;
}
}
class Apple {
Apple getPeeled() {
return Peeler.peel(this);
}
}
public class PassingThis {
public static void main(String[] args) {
new Person().eat(new Apple()); //一个语言现象,就是右边的赋值变量往往可以直接写出来,如左边的new Person(),new Apple()
}
}