Java-10-Method Rewriting

One: Understanding of method rewriting

Note: distinguish between overloading and rewriting
Insert picture description here

Two: practice

Example 1

Person.java

package com.xx.study;

public class Person {
    
    
	
	String name;
	int age;
	public Person() {
    
    }
	public Person(String name,int age) {
    
    
		this.name=name;
		this.age=age;
	}
	public void eat() {
    
    
		System.out.println("吃饭");
	}
	public void sleep(int time) {
    
    
		System.out.println("睡觉"+time+"小时");
		show();
	}
	private void show() {
    
    
		System.out.println("今天要早睡啊");
	}
	public Object info() {
    
    
		return null;
	}
}

Student.java

package com.xx.study;

public class Student extends Person {
    
    
	String major;

	public Student() {
    
    
	}

	public Student(String major) {
    
    
		this.major = major;
	}

	public void study() {
    
    
		System.out.println("专业是" + major);
	}

	// 对父类的eat方法重写
	public void eat() {
    
    
		System.out.println("吃减脂餐");
	}

	// 特殊情况,子类中不能重写父类中声明为private权限的方法,显示的还是父类的值
	public void show() {
    
    
		System.out.println("dd");
	}

	/*
	 * 父类Object的重写 父类重写的方法的返回值类型是A类型,
	 * 则子类重写的方法类型可以是A类或A的子类
	 * String是Object的子类
	 */
	public String info() {
    
    
		return null;
	}
}

PersonTest.java

package com.xx.study;

public class PersonTest {
    
    
  public static void main(String[] args) {
    
    
	Student s=new Student("计算机科学与技术");
	s.eat();
	s.sleep(10);
	s.study();
	
}
   
}

Example 2

Insert picture description here
Private cannot overwrite
Kids.java

package com.xzx.contact;

public class Kids extends ManKind{
    
    
  private int yearsOld;
  public Kids() {
    
    }
  public Kids(int yearsOld) {
    
    
	  this.yearsOld=yearsOld;
  }
  public int getyearsOld() {
    
    
	  return yearsOld;
  }
  public void setyearsOld(int yearsOld) {
    
    
	  this.yearsOld=yearsOld;
  }
  
  public void printAge() {
    
    
	  System.out.println(yearsOld);
  }
  public void employeed() {
    
    
	  System.out.println("Kids should study and no job");
  }
  
  
}

KidsTest.java

package com.xzx.contact;

public class KidsTest {
    
    
	public static void main(String[] args) {
    
    
		Kids someKids = new Kids();
		someKids.setSalary(100000);
		System.out.println(someKids.getSalary());
		Kids someKids2 = new Kids(1);
		System.out.println(someKids2.getyearsOld());
		someKids.employeed();
	}

}

Three: the difference between rewriting and reloading

Insert picture description here

Guess you like

Origin blog.csdn.net/x1037490413/article/details/109306606