码迷,mamicode.com
首页 > 编程语言 > 详细

Java - Thinking in Java 第5章 习题

时间:2015-07-11 22:58:48      阅读:369      评论:0      收藏:0      [点我收藏+]

标签:mystra   java   

1

//: Main.java

/**
 * String初始化
 */

class Test {
    String s;
}

class Main {
    public static void main(String[] args) {
        Test t = new Test();
        System.out.println("s = " + t.s);
    }
}
/**
 * Output:
 s = null
 *///:~

2

初始化效果相同, 成员变量定义初始化定义时确定, 构造初始化构造时确定.

//: Main.java

/**
 * 初始化
 */

class Test {
    String s1;
    String s2 = "haha";
    String s3;
    Test () {
        s3 = "hehe";
    }
}

class Main {
    public static void main(String[] args) {
        Test t = new Test();
        System.out.println("s1 = " + t.s1);
        System.out.println("s2 = " + t.s2);
        System.out.println("s3 = " + t.s3);    }
}
/**
 * Output:
 s1 = null
 s2 = haha
 s3 = hehe
 *///:~

3

//: Main.java

/**
 * 默认构造器
 */

class Test {
    Test () {
        System.out.println("This is Test");
    }
}

class Main {
    public static void main(String[] args) {
        Test t = new Test();
    }
}
/**
 * Output:
 This is Test
 *///:~

4

//: Main.java

/**
 * 默认构造器
 */

class Test {
    Test () {
        System.out.println("This is Test");
    }
    Test (String s) {
        System.out.println("Test : " + s);
    }
}

class Main {
    public static void main(String[] args) {
        Test t = new Test("Hello");
    }
}
/**
 * Output:
 Test : Hello
 *///:~

5

//: Main.java

/**
 * 构造器重载
 */

class Dog {
    Dog() {
        System.out.println("Wang! Wang! Wang!");
    }

    Dog(String s) {
        System.out.println("Barking!");
    }

    Dog(int i) {
        System.out.println("Howling!");
    }
}

class Main {
    public static void main(String[] args) {
        Dog d1 = new Dog();
        Dog d2 = new Dog("Hello");
        Dog d3 = new Dog(1);
    }
}
/**
 * Output:
 Wang! Wang! Wang!
 Barking!
 Howling!
 *///:~

6

//: Main.java

/**
 * 构造器重载-参数顺序不同
 */

class Dog {
    Dog() {
        System.out.println("Wang! Wang! Wang!");
    }

    Dog(String s, int i) {
        System.out.println("Barking!");
    }

    Dog(int i, String s) {
        System.out.println("Howling!");
    }
}

class Main {
    public static void main(String[] args) {
        Dog d1 = new Dog();
        Dog d2 = new Dog("Hello", 1);
        Dog d3 = new Dog(1, "Hello");
    }
}
/**
 * Output:
 Wang! Wang! Wang!
 Barking!
 Howling!
 *///:~

7

//: Main.java

/**
 * 默认构造器
 */

class Test {
    String s = "Hello World";
}

class Main {
    public static void main(String[] args) {
        Test t = new Test();
        System.out.println(t.s);
    }
}
/**
 * Output:
 Hello World
 *///:~

版权声明:本文为博主原创文章,未经博主允许不得转载。

Java - Thinking in Java 第5章 习题

标签:mystra   java   

原文地址:http://blog.csdn.net/caroline_wendy/article/details/46844651

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!