package com.learnjava.gj.oop;
/**
- USER : JACK
- DATE : 2021/11/20 19:36
- DESC : Person类是父类
*/
public class Person {
//成员变量 挂接到实例上 讲实例属性进行封装,通过特定方法进行访问
private String name;
private int age;
//构造方法
public Person(String name,int age){
this.name = name;
this.age = age;
}
//getter and setter
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 showInfo(){
System.out.println(this.name + " is "+this.age+" years old!");
}
}
Student
package com.learnjava.gj.oop;
/**
-
USER : JACK
-
DATE : 2021/11/20 19:40
-
DESC :学生子类 继承Person类部分方法和属性
*/
public class Student extends Person{
//独有属性
private String school;//构造方法
public Student(String name,int age,String school){
super(name,age);
this.school = school;
}
@Override
//重写父类showInfo()方法
public void showInfo(){
System.out.println(this.getName() + " is "+this.getAge()+" years old!,学校是:"+this.school);
}
}
MainTest
package com.learnjava.gj.oop;
/**
- USER : JACK
- DATE : 2021/11/20 19:47
- DESC :
*/
public class MainTest {
public static void showInfoP(Person p){
if(p instanceof Student){
p = (Student) p;
p.showInfo();
}else{
p.showInfo();
}
}
public static void main(String[] args) {
Student p = new Student("jack",12,"北高");
Person p1 = new Person("bob",23);
showInfoP(p1);
showInfoP(p);
}
}