创建父类
public class Uncle {
private String name;
private int age;
public Uncle(){
}
public Uncle(String name,int age){
this.name=name;
this.age=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;
}
@Override
public String toString() {
return "Uncle{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public void fahongbao(){
System.out.println("舅舅发红包");
}
}
创建子类一:
public class UncleOne extends Uncle{
public void fahongbao(){
System.out.println("大舅发红包");
}
public void songyan(){
System.out.println("大舅喜欢送烟");
}
}
创建子类二:
public class UncleTwo extends Uncle{
public void fahongbao(){
System.out.println("二舅发红包");
}
}
多态子类继承父类
public class Demo {
public static void main(String[] args) {
UncleOne dajiu=new UncleOne();
dajiu.fahongbao();
UncleTwo uncleTwo=new UncleTwo();
uncleTwo.fahongbao();
//多态 向上转型
Uncle dajiu1=new UncleOne();
dajiu1.fahongbao();
//子类独有的方在发生向上转型的时候无法在父类中使用
//dajiu1.songyan(); 会报错
UncleOne temp=(UncleOne)dajiu1;
temp.songyan();//可以调用子类独有的方法
Uncle erjiu=new UncleTwo();
erjiu.fahongbao();
//向下转型
Uncle uncle=new Uncle();
uncle.fahongbao();
public class Demo01 {
public static void main(String[] args) {
Uncle uncle1=new UncleOne();
Uncle uncle2=new UncleTwo();
if(uncle1 instanceof UncleOne){
UncleOne u1=(UncleOne) uncle1;
u1.fahongbao();
}
if (uncle2 instanceof UncleTwo){
UncleTwo u2=(UncleTwo) uncle2;
u2.fahongbao();
}
}