java:方法重写

子类重写父类的方法,只是重写编写方法体的代码;
如果父类的方法是public的,子类重写的时候就不能使用(比public更严格的)缺省以下
子类父类要么都是static的,要不就都是非static的
子类不能访问父类的私有东西

public class Person {

int age;
String name;
String sex;


public void setInfo(int age,String name,String sex){
	this.age=age;
	this.name=name;
	this.sex=sex;
}


public void showInfo(){
	System.out.println(this.age);
	System.out.println(this.name);
	System.out.println(this.sex);
}

public class Student extends Person {

String school;

// 重写方法快捷键ALT+/
public void setInfo(int age, String name, String sex) {

	System.out.println(age);
	System.out.println(name);
	System.out.println(sex);

};

@Override
public void showInfo() {
	System.out.println("以下是是父类方法的重写");
	System.out.println(this.age);
	System.out.println(this.name);
	System.out.println(this.sex);

}

public static void main(String[] args) {

	Student stu = new Student();
	stu.setInfo(2, "zhangsan", "男");
	stu.showInfo();
}
发布了18 篇原创文章 · 获赞 3 · 访问量 182

猜你喜欢

转载自blog.csdn.net/weixin_46037153/article/details/104425012
今日推荐