• 10月20日动手动脑


    1.

    class Grandparent
    {


    public Grandparent()
    {

    System.out.println("GrandParent Created.");

    }


    public Grandparent(String string)
    {

    System.out.println("GrandParent Created.String:" + string);

    }

    }

    class Parent extends Grandparent
    {


    public Parent()
    {

    //super("Hello.Grandparent.");

    System.out.println("Parent Created");

    // super("Hello.Grandparent.");

    }

    }

    class Child extends Parent
    {


    public Child()
    {

    System.out.println("Child Created");

    }

    }

    public class TestInherits
    {


    public static void main(String args[])
    {

    Child c = new Child();

    }

    }

    结果:

     通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。

    2.

    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

    结论:在“+”运算中,当任何一个对象与一个String对象,连接时,会隐式地调用其toString()方法,默认情况下,此方法返回“类名 @ + hashCode”。为了返回有意义的信息,子类可以重写toString()方法。

    3.

    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;

    }
    }

    结果:

     结论:子类的内容多于父类,不可以将子类赋给父类。

    4.

    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);
    }
    }

    结论:

    当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。
    这个特性实际上就是面向对象“多态”特性的具体表现。

  • 相关阅读:
    【python系列】安装完PyCharm创建项目提示No Python interpreter selected
    银联支付测试
    【linux系列】linux防火墙的关闭开启
    【linux系列】vmware12pro安装centos7
    【linux系列】安装虚拟机时候的3中网络模式
    JavaBean与Map<String,Object>相互转换
    【CSS系列】布局篇
    【CSS系列】对表单和数据表格应用样式
    【CSS系列】图像映射
    【Linux系列】find命令使用
  • 原文地址:https://www.cnblogs.com/buyaoya-pingdao/p/13866822.html
Copyright © 2020-2023  润新知