java從0單排之複習與面試題回顧——03

第三章:面向對象(上)
1.對象的比較,即“==”和equals()方法,”==“用於比較兩個變量的值是否相等,equals()用於比較兩個對象的內容是否一致。
    public class StringDemo4 {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        System.out.println(s1==s2);//false
        System.out.println(s1.equals(s2));//true
         
        String s3 = new String("hello");
        String s4 = "hello";//在方法區有這個常量值
        System.out.println(s3==s4);//false
        System.out.println(s3.equals(s4));//true
         
        String s5 = "hello";
        String s6 = "hello";
        System.out.println(s5==s6);//true
        System.out.println(s5.equals(s6));//true
    }
 
}

    public class StringDemo5 {
    public static void main(String[] args) {
        String s1  = "hello";
        String s2 = "world";
        String s3 = "helloworld";
        System.out.println(s3==s1+s2);//false(s1和s2是兩個變量是先開空間再拼接在一起,所以不和s3地址值一直)
        System.out.println(s3.equals(s1+s2));//true
        System.out.println(s3=="hello"+"world");//true(因爲"hello"和"world"是常量,所以先拼接再去找有沒有這個拼接後的常量,發現有,s3所以相等)
        System.out.println(s3.equals("hello"+"world"));//true
     
        //通過反編譯看源碼,我們知道這裏已經做好了處理
//      System.out.println(s3=="helloworld");
//      System.out.println(s3.equals("helloworld"));
    }
 
}

  
2.A a=new A(”tom“);具體過程: 棧內存中定義句柄a,堆內存中創建A的對象,屬性使用默認初始化的值,然後調用A的構造方法,進行屬性的賦值(所以構造方法被調用時,對象已經產生),然後a指向A對象。

3.finalize()方法是在對象被當成垃圾從內存中釋放前調用,而不是對象變成垃圾前調用。由於java的垃圾回收器不定時啓動,所以不能確定什麼時候調用finalize()方法。如果不啓動,就不會調用finalize()。爲此,java中提供了一個
    System.gc()方法來強制啓動垃圾回收器。

4.所以我們不能在任何方法體內的變量聲明爲靜態。

5.類是在第一次被使用的時候才被裝載的,而不是在程序啓動時就裝載程序中所有可能要用到的類。static修飾的變量,方法,代碼塊都是和class綁定的,和對象的創建無關,所以無論創建幾個對象,他們都只被執行一次。

6.當A類中的程序代碼要用到B類的實例對象,而B類中的程序代碼又要訪問A類中的成員,將B當做A的內部類是很有效的解決辦法。一個內部類可以訪問它的外部類的成員,反之不成立。
    class Outer
    {    
        int out_i=100;
        void test()
        {
            Inner in=new Inner();
            in.display();
        }

        class Inner()
        {
            void display()
            {
                System.out.print(out_i);
            }
        }
    }
    class Demo
    {
        public static void main(String [] args)
        {
            Outer out=new Outer();
            out.test();
        }
    }
(這裏笨小蔥想起一道筆試題,啓動4個線程,對於整數i,2個線程每次+1操作,2個線程每次-1操作。當時就是使用的內部類的程序代碼)


7內部類如何被外部引用,只需將內部類申明爲pulic。
    class Outer
    {
        private int size=10;
        public class Inner
        {
            public void  test()
            {
            System.out.print(size);
            }
        }
    }
    
    class Demo
    {
        public static void main(String [] args)
        {
            Outer out=new Outer();
            Outer.Inner in=out.new Inner();
            in.test();
        }
    }

發佈了35 篇原創文章 · 獲贊 15 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章