动手动脑
1 源代码
class Grandparent
{
public Grandparent()
{
System.out.println("GrandParent Created.");
}
public Grandparent(String string)
{
System.out.println("GrandParent Created.String:" + string);
}
}
class Parent11 extends Grandparent
{
public Parent11()
{
//super("Hello.Grandparent.");
System.out.println("Parent Created");
//super("Hello.Grandparent.");
}
}
class Child11 extends Parent11
{
public Child11() { System.out.println("Child Created");}
}
public class TestInherits
{
public static void main(String args[]) { Child11 c = new Child11();}
}
运行结果
GrandParent Created.
Parent Created
Child Created
结果分析
创建子类前会先调用父类的构造方法
去掉第一个注释号后运行结果
GrandParent Created.String:Hello.Grandparent.
Parent Created
Child Created
结果分析
可在子类中通过传参构造父类,父类构造过后将不再构造
去掉第二个注释程序报错
原因分析
报错内容 Constructor call must be the first statement in a constructor
通过super调用基类构造方法,必须是子类中的第一句
2. 为什么子类的构造方法在运行之前,必须调用父类的构造方法?能不能反过来?为什么不能反过来?
构造函数(constructor)是一种特殊的方法 。主要用来在创建对象时初始化对象, 即为对象成员变量赋初始值,总与new运算符一起使用在创建对象的语句中 。特别的一个类可以有多个构造函数 ,可根据其参数个数的不同或参数类型的不同来区分它们 即构造函数的重载。构造函数的功能主要用于在类的对象创建时定义初始化的状态。
构造一个对象,先调用其构造方法,来初始化其成员函数和成员变量。
子类拥有父的成员变量和成员方法,如果不调用,则从父类继承而来的成员变量和成员方法得不到正确的初始化。
不能反过来调用也是这个原因,因为父类根本不知道子类有神魔变量而且这样一来子类也得不到初始化的父类变量,导致程序运行出错!
3. 源代码
public class Fruit
{
public String toString()
{
return "Fruit toString.";
}
public static void main(String args[])
{
Fruit f=new Fruit();
System.out.println("f="+f);
System.out.println("f="+f.toString());
}
}
运行结果
f=Fruit toString.
f=Fruit toString.
结果分析
在“+”运算中,当任何一个对象与一个String对象,连接时,会隐式地调用其toString()方法,默认情况下,此方法返回“类名 @ + hashCode”
4. 源代码
class Mammal{}
class Dog extends Mammal {}
class Cat extends Mammal{}
public class TestCast
{
public static void main(String args[])
{
Mammal m;
Dog d=new Dog();
Cat c=new Cat();
m=d;
//d=m;
d=(Dog)m;
//d=c;
//c=(Cat)m;
}
}
运行未报错
去掉第一个注释符号 发生编译错误 Type mismatch: cannot convert from Mammal to Dog
去掉第二个注释符号 发生编译错误 Type mismatch: cannot convert from Cat to Dog
去掉最后一个注释符号 发生运行错误
5. 源代码
public class ParentChildTest {
public static void main(String[] args) {
Parent parent=new Parent();
parent.printValue();
Child child=new Child();
child.printValue();
parent=child;
parent.printValue();
parent.myValue++;
parent.printValue();
((Child)parent).myValue++;
parent.printValue();
}
}
class Parent{
public int myValue=100;
public void printValue() {
System.out.println("Parent.printValue(),myValue="+myValue);
}
}
class Child extends Parent{
public int myValue=200;
public void printValue() {
System.out.println("Child.printValue(),myValue="+myValue);
}
}
运行结果
Parent.printValue(),myValue=100
Child.printValue(),myValue=200
Child.printValue(),myValue=200
Child.printValue(),myValue=200
Child.printValue(),myValue=201
结果分析
当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。
如果子类与父类有相同的字段,则子类中的字段会代替或隐藏父类的字段,子类方法中访问的是子类中的字段(而不是父类中的字段)。如果子类方法确实想访问父类中被隐藏的同名字段,可以用super关键字来访问它。
如果子类被当作父类使用,则通过子类访问的字段是父类的。

浙公网安备 33010602011771号