java 構造函數

  1. 構造函數的基本應用
  2.  1 package cn.sasa.demo1;  2 
     3 public class Computer {  4 
     5     //構造函數,能夠在建立對象時,爲一些變量給定初始值  6     //若是不寫構造函數,編譯時默認會添加一個空參的構造函數  7     //public Computer() {}  8     
     9     //若是寫了構造函數,那麼編譯時不會再添加空參的構造函數 10     //在new對象時,由於沒有空參的構造函數,因此在new的時候,必須調用有參的構造函數
    11     public Computer(String name) { 12         this.name = name; 13  } 14     
    15     //構造函數能夠重載
    16     public Computer(String name, double price) { 17         this.name = name; 18         this.price = price; 19  } 20     
    21     //構造函數能夠爲成員變量賦值,但只有在new的時候執行一次,以後不會再執行 22     //因此還須要get和set方法,使這以後還能夠修改變量值。
    23     private String name; 24     public String getName() { 25         return this.name; 26  } 27     public void setName(String name) { 28         this.name = name; 29  } 30     
    31     private double price; 32     public double getPrice() { 33         return this.price; 34  } 35     public void setPrice(double price) { 36         this.price = price; 37  } 38     
    39 }
     1 package cn.sasa.demo1;  2 
     3 public class Test {  4     public static void main(String[] args) {  5         //由於沒有空參的構造函數,因此必須調用有參的構造函數。  6         //new的"()",就是在調用構造函數
     7         Computer com = new Computer("華碩");  8         System.out.println(com.getName() + "======" + com.getPrice());  9         com.setName("聯想"); 10  System.out.println(com.getName()); 11         
    12         Computer com1 = new Computer("宏基" , 5000); 13         System.out.println(com1.getName() + "======" + com1.getPrice()); 14  } 15 }
  3. this()和super()
  • this()調用的是本類的構造函數,super()調用的是父類的構造函數
  • this()和super()在同一個構造方法中必須只有其中一個,而且放在第一行

 

 1 package cn.sasa.demo1;  2 
 3 public class NoteComputer  extends Computer{  4     public NoteComputer() {  5         //子類繼承父類,在構造函數的第一行默認添加了super()  6         //可是父類重寫了構造方法,沒有空參的構造方法,就會報錯  7         //解決方法是用super()調用父類的其中一個構造方法
 8         super("");  9  } 10     
11     public NoteComputer(boolean isTouch) { 12         //this()調用的是本類的構造方法
13         this(); 14         this.IsTouchScreen = isTouch; 15  } 16     
17     private boolean IsTouchScreen; 18     
19     public boolean getIsTouchScreen() { 20         return this.IsTouchScreen; 21  } 22     
23     public void setIsTouchScreen(boolean isTouch) { 24         this.IsTouchScreen = isTouch; 25  } 26 }
相關文章
相關標籤/搜索