Javaコードブロックの詳細説明
13415 ワード
1、構造方法
1.1概念構築方法は、クラスと同名であり、戻り値タイプが同名のクラスタイプである特殊な方法である. オブジェクトの作成は、構築方法によって行われます. その機能は、主にオブジェクトの作成またはオブジェクトの初期化を完了することである. クラスがnewオブジェクトをインスタンス化すると、構造メソッドが自動的に呼び出されます. の構築方法は、他の方法と同様に再ロードすることもできます(方法名が同じ+パラメータリストが異なる).
1.2形式
無参でも有参でも修飾子クラス名(パラメータリスト){コード......}
構築方法:
構築方法:
2、構築コードブロックとローカルコードブロック
2.1コードブロックを構築する{}1、クラスの内部、メソッドの外部、のコードブロック. 2は、一般に、構築方法における共通コードを抽出するために用いられる. 3、構築方法を呼び出すたびに構築コードブロックnew new が呼び出される.4、構築方法に優先するロード
2.2ローカルコードブロック1、メソッド内のコードブロック 2、変数を制御するために一般的に用いられる作用範囲は、括弧を出すと失効する である.3、変数の範囲が小さいほど良い、メンバー変数にスレッドセキュリティの問題がある
1.1概念
1.2形式
無参でも有参でも修飾子クラス名(パラメータリスト){コード......}
構築方法:
public class Test1_Constructor {
public static void main(String[] args) {
//
//3、new Person();
Person p = new Person();
//4、new Person("rose");
Person p2 = new Person("rose");
}
}
// Person
class Person{
// ( ){ }
//1、 -- !!
//5、 , , !!
public Person() {
System.out.println(" ...");
}
// : 1、 2、
//2、 :
public Person(String name) {
System.out.println(" ..."+name);
}
}
構築方法:
public class Test2_Constructor2 {
public static void main(String[] args) {
//
//1、
Person2 p = new Person2();
//2、
Person2 p2 = new Person2("jack");
}
}
// Person2
class Person2{
//4、 : setXxx()
private String name;
public Person2() {
System.out.println(" ");
}
public Person2(String n) {
//3、 , name
name = n ;
System.out.println(name);
}
}
2、構築コードブロックとローカルコードブロック
2.1コードブロックを構築する{}
public class Test3_Block {
public static void main(String[] args) {
// Person3
//2、 , ,,
Person3 p = new Person3(); //
Person3 p2 = new Person3("jack"); //
}
}
// Person3
class Person3{
//1、 :
//3、 : !!!
String country ;
{
country = " ";//
}
//
public Person3() {
System.out.println(" "+country);
}
//
public Person3(String n) {
System.out.println(" "+n+country);
}
}
2.2ローカルコードブロック
public class Test4_Block2 {
public static void main(String[] args) {
//
Person4 p = new Person4();//
p.eat();
}
}
// Person4
class Person4{
//
//
public void eat() {
//1、 : + +
{
int i = 10;
System.out.println(i);
}
System.out.println(" ");
// System.out.println(i); // , i
}
}