zoukankan      html  css  js  c++  java
  • JAVA基础--方法的重写overwrite 和 重载overload

    重写 overwrite或者override: 相同的方法名称, 参数列表和返回类型

    重载overload: 方法有相同的名字, 但是参数不同 (参数个数不同, 参数类型不同, 其中一个不同即可),

    重写的方法的访问权限不能比父类的方法权限更严格.

    比如父类的方法是protected, 那么子类覆写的方法的权限是protected或者public

    overwrite:

    class Person {
        private String name;
        private int age;
        public void setName(String name){this.name=name;}
        public void setAge(int age) {this.age=age;}
        public String getName(){return name;}
        public int getAge(){return age;}
        public String getInfo() {
              return "Name: "+ name + "
    " +"age: "+ age;
      }
    }
    
    class Student extends Person {
        private String school;
        public String getSchool() {return school;}
        public void setSchool(String school)
        {this.school =school;}
        public String getInfo() {
          return  "Name: "+ getName() + "
    age: "+ getAge() 
                        + "
    school: "+ school;
    		}
    }
    
    public class TestOverWrite {
    public static void main(String arg[]){
            Student student = new Student();
            Person person = new Person();
            person.setName("none");
            person.setAge(1000);
            student.setName("John");    
            student.setAge(18);
            student.setSchool("SCH");
            System.out.println(person.getInfo());
            System.out.println(student.getInfo());
        }
    }
    

    overload:

    public class Test {
    	void max(int a , int b) {
    		System.out.println( a > b ? a : b );
    	}
    	
    	void max(short a , short b) {
    		System.out.println("short");
    		System.out.println( a > b ? a : b );
    	}
    	
    	void max(float a, float b) {
    		System.out.println( a > b ? a : b );
    	}
    	
    	public static void main(String[] args) {
    		Test t = new Test();
    		t.max(3, 4);
    		short a = 3;
    		short b = 4;
    		t.max(a, b);
    	}
    }
    

      

      

  • 相关阅读:
    【转】acm小技巧
    poj-1703-Find them, Catch them
    poj-1611-The Suspects
    poj-2236-Wireless Network
    hdu-4496-D-City
    hdu-1213-How Many Tables
    hdu-1856-More is better
    gcd和ex_gcd
    递归趣文
    算法实质【Matrix67】
  • 原文地址:https://www.cnblogs.com/wujixing/p/5320233.html
Copyright © 2011-2022 走看看