Uncle:
public class Uncle {
private String name ;
private int age ;
public Uncle(){
}
public Uncle(String name , int age){
this.name = name ;
this.age = age ;
}
public void fahongbao(){
System.out.println("发红包");
}
public String getName(){
return name ;
}
@Override
public String toString() {
return "Uncle{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
UncleOne:
public class UncleOne extends Uncle {
public void faHongbao(){
System.out.println("发红包");
}
public void songyan(){
System.out.println("送烟");
}
}
UncleTwo :
public class UncleTwo extends Uncle {
public void faHongbao(){
System.out.println("发红包");
}
}
Dome01:
public class Dome01 {
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 uncleTwo1 = new UncleTwo() ;
UncleTwo temp1 = (UncleTwo) uncleTwo;
temp.faHongbao();
}
}
Dome02:
public class Dome02 {
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();
}
}
}