zoukankan      html  css  js  c++  java
  • Java基础19-封装、方法重载、构造方法(构造函数)

    1.封装

    • 封装就是把不想或者不该告诉别人的东西隐藏起来,把可以告诉别人的公开
    • 做法:修改属性的访问权限来限制对属性的访问。并为每一个属性创建一对取值方法和赋值方法,用于对这些属性的访问
     1 class Dog{
     2     String name;//成员变量
     3     int age;
     4     private char genter;//加private变为私有属性,要提供方法才能在外部进行调用
     5     
     6     public void setGenter(char genter){
     7         //加if语句可以防止乱输入
     8         if(genter=='男'||genter=='女'){
     9             this.genter=genter;//this.name,这个name为成员变量
    10         }else{
    11             System.out.println("请输入正确的性别");
    12         }
    13     }
    14     public char getGenter(){
    15         return this.genter;
    16     }
    17 
    18 }
    19 public class Test1{
    20     public static void main(String[] args){
    21         Dog one=new Dog();
    22         one.setGenter('女');
    23         System.out.println(one.getGenter());
    24         
    25     }
    26 }

     2.方法的重载

      方法的重载是指一个类中可以定义有相同的名字,但参数不同的多个方法,调用时会根据不同的参数列表选择对应的方法。

     1 class Cal{
     2     public void max(int a,int b){
     3         System.out.println(a>b?a:b);
     4     }
     5     public void max(double a,double b){
     6         System.out.println(a>b?a:b);
     7     }
     8     public void max(double a,double b,double c){
     9         double max=a>b?a:b;
    10         System.out.println(max>c?max:c);
    11     }
    12 
    13 }
    14 public class Test1{
    15     public static void main(String[] args){
    16         Cal one=new Cal();
    17         one.max(88.9,99.3,120);
    18         
    19     }
    20 }

     3.构造方法(构造函数)

    • 使用new+构造方法创建一个新的对象
    • 构造函数是定义在java类中的一个用来初始化对象的函数
    • 构造函数与类同名且没有返回值
     1 class Dog{
     2     private String name;
     3     private int age;
     4     Dog(String name,int age){//构造方法,public可加可不加
     5         this.name=name;
     6         this.age=age;
     7         System.out.println("名字:"+this.name+"年龄:"+this.age);
     8     }
     9     Dog(){
    10     }
    11     void get(){//普通方法,public可写可不写
    12         System.out.println("我是一个普通方法");
    13     }
    14 
    15 }
    16 public class Test1{
    17     public static void main(String[] args){
    18         Dog one=new Dog("小明",26);
    19         Dog two=new Dog();
    20         one.get();
    21         two.get();
    22             
    23     }
    24 }
  • 相关阅读:
    高斯消元学习
    HDU 4596 Yet another end of the world(解一阶不定方程)
    Codeforces Round #318 div2
    HDU 4463 Outlets(一条边固定的最小生成树)
    HDU 4458 Shoot the Airplane(计算几何 判断点是否在n边形内)
    HDU 4112 Break the Chocolate(简单的数学推导)
    HDU 4111 Alice and Bob (博弈)
    POJ 2481 Cows(线段树单点更新)
    HDU 4288 Coder(STL水过)
    zoj 2563 Long Dominoes
  • 原文地址:https://www.cnblogs.com/shenhainixin/p/9981976.html
Copyright © 2011-2022 走看看