继承多态

在子类中,若要调用父类中被覆盖的方法,可以使用super关键字。

源代码

package Super;

 

public class Super {

public static void main(String args[]) {

String title="恭贺新春";

String content="\t岁岁平安\n\t身体健康\n\t万事如意\n";

ChristmasCard card=new ChristmasCard(title,content);

card.showCard();

//Card ca=new Card();

//Card();

}

}

class Card{

String title;

Card(){

title="Happy new year";

//System.out.println(title);

}

Card(String title){

this.title=title;

}

public String getTitle() {

return title;

}

}

 

class ChristmasCard extends Card

{

String content;

ChristmasCard(String title,String content){

//super();

super(title);//用super调用父类的Card(title);

this.content=content;

}

public void showCard()

{

System.out.println("\t"+getTitle());

System.out.printf("%s",content);

}

}

运行结果

类型转换

源代码

package Duotai;

class Mammal{}

class Dog extends Mammal {}

class Cat extends Mammal{}

 

public class TestCast

{

public static void main(String args[])

{

Mammal m = null;

Dog d=new Dog();

Cat c=new Cat();

//Mammal m=new Mammal();

m=d;//可以直接将子类对象付给父类

//d=m;//不能将父类对象付给子类

d=(Dog)m;//父类强制转换成子类

//d=c;//子类直接不能转换

//m=c;

c=(Cat)m;//如果没有m=c;就不能将m转换为cat类型

 

}

}

运行结果

运行以下代码

猜测结果

100

200

200

200

201

源代码

package Duotai;

 

//import Duotai1.Parent;

 

public class ParentChildTest {

public static void main(String[] args) {

Parent parent=new Parent();

/*Parent parent2=new Parent();

parent2=parent;*/

parent.printValue();//100

Child child=new Child();

child.printValue();//200

 

parent=child;

/*

 * 将parent类中的myValue值设定为static

 * 然后执行parent.myValue++;

 * 创建新父类parent2,调用printValue();函数

 * 最终可以看出parent中的 myValue值变为101

 * */

parent.myValue++;//将父类的myValue进行了+1操作

Parent parent2=new Parent();

parent2.printValue();//101

//child.myValue++;

 /*

  * 在有child.myValue++;之后parent.printValue();输出的201

  * 没有调用child.myValue++时,parent.printValue();输出的是200

  * */

parent.printValue();//调用的是Child.printValue()

 

child.printValue();//200

 

((Child)parent).myValue++;//等价于child.myValue++;

parent.printValue();//201

child.printValue();//201

 

}

}

 

class Parent{

public static int myValue=100;

public void printValue() {

System.out.println("Parent.printValue(),ParentValue="+myValue);

}

}

class Child extends Parent{

public int myValue=200;

public void printValue() {

System.out.println("Child.printValue(),ChildValue="+myValue);

}

}

运行结果

1)当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。

2)这个特性实际上就是面向对象“多态”特性的具体表现。

3)如果子类与父类有相同的字段,则子类中的字段会代替或隐藏父类的字段,子类方法中访问的是子类中的字段(而不是父类中的字段)。如果子类方法确实想访问父类中被隐藏的同名字段,可以用super关键字来访问它。

4)如果子类被当作父类使用,则通过子类访问的字段是父类的!

 

posted on 2017-11-09 16:10  王行行  阅读(139)  评论(0编辑  收藏  举报

导航