java是面向对象的变成语言。封装继承多态,这种机制使得程序扩展性很强。
基类的引用指向其子类的对象叫向下转型。
子类对象转换成基类叫向上转型。
好处就是,举个例子。如果没有继承就得写三个方法。- class Person{
- public String colour="黄色";
- public void outColour(){
-
- System.out.println("皮肤颜色为"+colour);
- }
- }
- class BlackPerson{
- public String colour="黑色";
- public void outColour(){
- System.out.println("皮肤颜色为"+colour);
- }
- }
- class WhitePerson{
- public String colour="白色";
- }
- public class Test4 {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Person p=new Person();
- WhitePerson wp=new WhitePerson();
- BlackPerson bp=new BlackPerson();
- outColour( p);
- outColour(wp);
- outColour(bp);
- }
- public static void outColour(Person p){
- System.out.println("皮肤颜色为"+p.colour);
- }
- public static void outColour(WhitePerson wp){
- System.out.println("皮肤颜色为"+wp.colour);
- }
- public static void outColour(BlackPerson bp ){
- System.out.println("皮肤颜色为"+bp.colour);
- }
-
-
- }
复制代码 有了继承,多态性就可以这样写,更容易扩展,主要代码不必更改,大概就这个意思,水平有限,,- class Person{
- public String colour="黄色";
- public void colour(){
-
- System.out.println("皮肤颜色为"+colour);
- }
- }
- class BlackPerson extends Person{
- public String colour="黑色";
- public void colour(){
- System.out.println("皮肤颜色为2"+colour);
- }
- }
- class WhitePerson extends Person{
- public String colour="白色";
- public String Language="英语";
- public void colour(){
- System.out.println("皮肤颜色为3"+colour);
- }
- }
- public class Test4 {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Person p=new Person();
- Person wp=new WhitePerson();
- Person bp=new BlackPerson();
- colour2( p);
- colour2(wp);
- colour2(bp);
- }
- public static void colour2(Person p){
- p.colour();
- }
-
-
- }
复制代码 |