类的多态
作者:互联网
类的重载
在同一个类中,允许同时存在多个同名方法,只要这些方法的参数个数或类型不同即可。
// 向上转型:将子类对象看做是父类对象 class A{ public static void draw(A a){ //A的静态方法 System.out.println("调用该方法,draw一个A类的图像"); } } public class Parallelogram extends A{ public static void main(String[] args) { Parallelogram b = new Parallelogram(); draw(b); //调用父类A的方法,draw一个A的子类的图像 } }
// 向上转型 class A{ public static void draw(A a){ //A的静态方法 System.out.println("调用该方法,draw一个A类的图像"); } } public class Parallelogram extends A{ public static void main(String[] args) { A a = new Parallelogram(); //将子类对象看作是父类对象进行创建 // Parallelogram c = a; //不能父类的对象直接被赋值给子类 会报错 Parallelogram c = (Parallelogram) a; // 将父类对象通过显示类型转换为子类后,可被赋值给子类的对象 draw(c); } }
public class Test { public static void main(String[] args) { A a1 = new A1(); a1.Eat("a1","ffa1"); A1 aa1 = (A1)a1; aa1.Eat("aa1","ffaa1"); } } class A{ public void Eat (String nm,String ffa){ System.out.println(nm+":方法为"+ffa); } } class A1 extends A{ } /* a1:方法为ffa1 aa1:方法为ffaa1 */
instanceof关键字
判断父类对象是否为子类的实例,或者某个类是否实现了某个接口。
public class Test { public static void main(String[] args) { A a1 = new A1(); a1.Eat("a1","ffa1"); if (a1 instanceof A1) { System.out.println("a1是A1的实例"); A1 aa1 = (A1)a1; aa1.Eat("aa1","ffaa1"); }else{ System.out.println("a1不是A1的实例"); } } } class A{ public void Eat (String nm,String ffa){ System.out.println(nm+":方法为"+ffa); } } class A1 extends A{ } /* a1:方法为ffa1 a1是A1的实例 aa1:方法为ffaa1 */
抽象类与抽象方法
//抽象类 意义:单纯被继承 [权限修饰符]abstract class 类名{ // 抽象方法 继承抽象类的所有子类 都要重写抽象类中的抽象方法 [权限修饰符] abstract 方法返回值类型 方法名(参数列表); //无方法体 }
public class GoShopping { public static void main(String[] args) { Shopping tb = new TBShopping(); tb.market = "淘宝"; tb.goods = "衣服"; System.out.println("在"+tb.market+tb.shop()+tb.goods); Shopping xx = new XXShopping(); xx.market = "实体店"; xx.goods = "鞋子"; System.out.println("在"+xx.market+xx.shop()+xx.goods); } } // 抽象类 买东西 abstract class Shopping { public String market; //购买地 public String goods; //商品 public abstract String shop(); //抽象方法 购买行为 } class TBShopping extends Shopping{ //网购类 public String shop(){ return "网购"; } } class XXShopping extends Shopping{ //线下购类 public String shop(){ return "线下买"; } } /*在淘宝网购衣服 在实体店线下买鞋子*/
public class GoShopping {
public static void main(String[] args) {
Shopping tb = new TBShopping();
tb.market = "淘宝";
tb.goods = "衣服";
System.out.println("在"+tb.market+tb.shop()+tb.goods);
Shopping xx = new XXShopping();
xx.market = "实体店";
xx.goods = "鞋子";
System.out.println("在"+xx.market+xx.shop()+xx.goods);
}
}
// 抽象类 买东西
abstract class Shopping {
public String market; //购买地
public String goods; //商品
public abstract String shop(); //抽象方法 购买行为
}
class TBShopping extends Shopping{ //网购类
public String shop(){
return "网购";
}
}
class XXShopping extends Shopping{ //线下购类
public String shop(){
return "线下买";
}
}
/*在淘宝网购衣服
在实体店线下买鞋子*/
标签:String,多态,public,a1,xx,tb,class 来源: https://www.cnblogs.com/jxba/p/16481393.html