java學習中,instanceof 關鍵字 和 final 關鍵字、值的傳遞(java 學習中的小記錄)
作者:王可利(Star·星星)
instanceof 關鍵字
作用:
1.用來判斷某個對象是否屬於某一個類。
2.instanceof 關鍵字使用的前提:對象指定的類有繼承關系或者實現關系
3.強制類型轉換會用到 instanceof 關鍵字。
如:
Student s = (Student)new Person();//要想這麼做,必須滿足Student繼承Person。
boolean res = s instanceof Person
if( res){
Student s = (Student)new Person();
}
代碼如下:
1 package study;
2
3 class Person{
4 String name;
5 public Person(String name) {
6 this.name = name;
7 }
8 public Person() {}
9 }
10
11 class Student extends Person{
12
13 }
14
15 public class star {
16 public static void main(String[] args) {
17 Person star = new Person("星星");
18 boolean result1 = star instanceof Person;
19 System.out.println(result1);//ture
20
21 Student s = new Student();//默認父類的無參構造
22
23 boolean result2 = s instanceof Person;
24 System.out.println(result2);//ture
25 }
26
27 }
final 關鍵字(修飾符,最終的)
1.如果用一個final 關鍵字修飾一個基本數據類型變量,改變了就不能重新賦值。第一次的結果為最終結果。
2.如果用final修飾引用數據類型,引用數據類型的變量就不能再賦值。
如:這樣是錯的。
final Yuan yuan = new Yuan(10);
yuan = new Yuan(100);//無法重新賦值
3.如果final修飾一個方法,方法就不能被重寫。
4.如果final修飾一個類,那麼這個類就不能被繼承。
5.final 修飾的變量必須要初始化,不然會報錯。
1 package study;
2
3 class Yuan{
4 int r;
5 final double pai = 3.14;//應該是一個不變的量,不然下面參數 給了 不是3.14 就會被修改。類似常量
6
7 public Yuan(int r/*,double pai*/) {
8 this.r = r;
9 /* this.pai = pai;*/
10 }
11
12 public void area(){
13 System.out.println("圓的面積是"+r*r*pai);
14 }
15 }
16
17 public class star {
18 public static void main(String[] args) {
19 Yuan yuan = new Yuan(10/*,3.14*/);//不給修飾會被修改
20 yuan.area();
21 }
22 }
如何用final表示常量:
格式:
public final static 基本數據類型 變量名
值的傳遞
基本數據類型之間賦值,實際是將變量的值賦給另外一個變量。
參數如果是引用類型,傳遞參數是參數的引用類型數據的地址。
引用類型:類、接口、數組
1 package study;
2
3 public class star {
4 public static void main(String[] args) {
5
6 //需求:定義兩個整形的數,用一個方法來交換兩個數
7 int a = 10;
8 int b = 20;
9 change(a, b);
10 System.out.println("a = "+a+",b = "+b);//10.20
11
12 //需求:定義一個數組,交換兩個數的位置
13 int[] arr = {10,20};
14 changeArr(arr);//20,10
15 System.out.println("arr[0] = "+arr[0]+"arr[1] = "+arr[1]);
16 }
17
18 public static void change(int a,int b){
19 int temp = a;
20 a = b;
21 b = temp;
22 }
23 public static void changeArr(int[] arr){
24 int temp = arr[0];
25 arr[1] = arr[0];
26 arr[0] = temp;
27 }
28 }