package com.neusoft.override;
public class A {
public String toString() {
return "123456";// 继承Object并重写
}
int a = 2;
public void func() {
System.out.println("1111111111");
}
public static void main(String[] args) {
A a = new A();
System.out.println(a);// 等同于a.toString()默认
}
}
package com.neusoft.override;
/**
* 继承多态
* 满足多态的条件:
* 1.要有继承关系
* 2.方法重写
* 3.父类的引用指向子类的对象
* @author Administrator
*
*/
public class B extends A {
int a = 2;
public void func() {
System.out.println("2222222222");
}
public static void main(String[] args) {
// B b = new B();
// b.func();//2222222222
// System.out.println(b.a);//2
//多态
A x = new B();//父类引用指向子类
x.func();//无论如何,涉及到重写,就执行子类2222222222
System.out.println(x.a);//1
A a = new A();
a.func();//1111111111
}
}
package com.neusoft.override;
/**
* 方法的覆盖override: /重写rewrite
* 1.要有继承关系
* 2.子类要重写父类中的方法,要求子类中的方法完全相同(访问权限,方法名称,参数,返回值类型)
* 3.为什么要使用方法重写?子类的方法对象父类方法的拓展与改造
*
*/
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void printInfo() {
System.out.println(name+"----"+age);
}
}
package com.neusoft.override;
public class Student extends Person{
private String school;
public String getSchool() {
return school;
}
public void getSchool(String school) {// overload 重载
this.school = school;// 初始化
}
public void printInfo(){
setAge(2);
System.out.println(getName()+getAge()+school);
}
public static void main(String[] args) {
Student student = new Student();
student.printInfo();
Person person = new Person();
person.printInfo();
}
}