zoukankan      html  css  js  c++  java
  • Java重载、构造函数和this、static要点

     一、重载函数

    • 类中多个同名的方法名
    • 靠参数来区分

      

    class Person{
          int age;
          String name;
          void  set(int a){
                age = a;
          }
          void set(String s){
                name = s;
          }  
    }

    二、构造函数

    • 没有返回值
    • 每个类都有构造函数,若没有写,编译器会自动添加
    • 如果类中写有其他有参构造函数而又没有写默认构造函数,这时new无参构造函数则会出错,因为编译器不会自动添加默认构造函数了。

      

    public class Person {
        public static void main(String agrc[]){
            //下行代码报错,已写有参构造函数,编译器不会自动添加默认构造函数了
            Dog d = new Dog();
        }
    }
    class Dog{
        Dog(int age){
            
        }
    }

    三、this代表调用这个函数的对象

      

    public class Person {
        int age;
        String name;
        String sex;
        Person(){
            
        }
        Person(int age, String name){
            //用法一:参数和成员变量同名时使用
            this.age = age;
            this.name = name;
        }
        Person(int age, String name, String sex){
            //用法二:调用构造函数,只能调用一个且写在代码第一行
            this(age, name);
            this.sex = sex;
        }
    }

     四、static静态关键字

      

    public class Person {
        public static void main(String agrc[]){
            Dog.age = 21;//可使用类名来调用(可没有对象)
        }
    }
    class Dog{
        static int age;
        static{
            //静态代码块,可用于给静态成员变量赋初值
        }
        static void set(){
            age = 30;//静态方法中要使用静态成员变量,不能使用this
        }
    }
  • 相关阅读:
    玩家上线
    小退
    GS发包到MS
    share初始化
    3 水仙花数
    The left-hand side of an assignment must be a variable,代码中使用了中文的字符
    Mac Sublime Text 浏览器 设置快捷键 让html文件在浏览器打开
    2 质数求解
    1 斐波那契的兔子
    18 赛手的名单
  • 原文地址:https://www.cnblogs.com/qiu520/p/4098213.html
Copyright © 2011-2022 走看看