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 + "\n" +"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() + "\nage: "+ getAge() 
                    + "\nschool: "+ 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);
	}
}

  

 

  

posted @ 2016-03-25 17:10  wujixing909  阅读(589)  评论(0编辑  收藏  举报