溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java基礎:封裝、方法重載、構造方法是什么

發(fā)布時間:2020-10-28 13:46:24 來源:億速云 閱讀:132 作者:小新 欄目:編程語言

這篇文章主要介紹Java基礎:封裝、方法重載、構造方法是什么,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

1.封裝

  • 封裝就是把不想或者不該告訴別人的東西隱藏起來,把可以告訴別人的公開
  • 做法:修改屬性的訪問權限來限制對屬性的訪問。并為每一個屬性創(chuàng)建一對取值方法和賦值方法,用于對這些屬性的訪問
  class Dog{ 
      String name;//成員變量 
      int age; 
     private char genter;//加private變?yōu)樗接袑傩?,要提供方法才能在外部進行調(diào)用 
       
      public void setGenter(char genter){ 
          //加if語句可以防止亂輸入 
          if(genter=='男'||genter=='女'){ 
              this.genter=genter;//this.name,這個name為成員變量
          }else{
              System.out.println("請輸入正確的性別");
          }
      }
      public char getGenter(){
          return this.genter;
      }
  
  }
  public class Test1{
      public static void main(String[] args){
          Dog one=new Dog();
          one.setGenter('女');
          System.out.println(one.getGenter());
          
      }
  }

2.方法的重載

  方法的重載是指一個類中可以定義有相同的名字,但參數(shù)不同的多個方法,調(diào)用時會根據(jù)不同的參數(shù)列表選擇對應的方法。

  class Cal{ 
      public void max(int a,int b){ 
          System.out.println(a>b?a:b); 
      } 
      public void max(double a,double b){ 
          System.out.println(a>b?a:b); 
      } 
      public void max(double a,double b,double c){ 
          double max=a>b?a:b;
          System.out.println(max>c?max:c);
      }
  
  }
  public class Test1{
      public static void main(String[] args){
          Cal one=new Cal();
          one.max(88.9,99.3,120);
          
      }
  }

3.構造方法(構造函數(shù))

  • 使用new+構造方法創(chuàng)建一個新的對象
  • 構造函數(shù)是定義在java類中的一個用來初始化對象的函數(shù)
  • 構造函數(shù)與類同名且沒有返回值
  class Dog{ 
      private String name; 
      private int age; 
      Dog(String name,int age){//構造方法,public可加可不加 
          this.name=name; 
          this.age=age; 
          System.out.println("名字:"+this.name+"年齡:"+this.age);
      } 
      Dog(){
      }
      void get(){//普通方法,public可寫可不寫
          System.out.println("我是一個普通方法");
      }14 15 }16 public class Test1{
      public static void main(String[] args){
          Dog one=new Dog("小明",26);
          Dog two=new Dog();
          one.get();
          two.get();
              
      }
  }

以上是Java基礎:封裝、方法重載、構造方法是什么的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI