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
*///:~
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-02 00:52:23