zoukankan      html  css  js  c++  java
  • ppt动手动脑4

    1.

     父类:

    public class Father {
        public void showOut()
        {
            System.out.println("这是父类方法!");
        }
    }

    子类:

    public class Son extends Father{
        public void showOut()
        {
            super.showOut();
            System.out.println("这是子类的方法!");
        }
    }
        public static void main(String[] args) {
            Son son=new Son();
            son.showOut();
        }

    运行结果:

     由此可见子类可以覆盖父类的方法,但是要求子类的方法和父类的方法一模一样,要不会变成重载。

    在子类中可以通过super调用父类的方法或成员变量,但是不能重载final方法和静态方法。

    2.

     测试代码:

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

    运行结果:

     由此可见子类在调用构造方法时会先调用父类的构造方法。

    作如下修改观察输出:

    class Parent extends Grandparent
    {
    
    
        public Parent()
         {
    
                //super("Hello.Grandparent.");
    
                System.out.println("Parent Created");
        
           // super("Hello.Grandparent.");
    
          }
    
    }

     在作如下修改:

     发现报错了,可见通过super调用构造方法必须是子类构造方法的第一句。

    3.

     这里main方法实际调用了public void println(objiect x)

    这一方法内部调用了String的valueOf()方法,valueOf()方法又调用了

    Object.toString()方法:

    public String toString() {
            return getClass().getName() + "@" + Integer.toHexString(hashCode());
        }

    所以输出了一堆奇怪的运行结果。

    4.

     运行结果:

     在对象与String类型进行+运算时会调用对象的toString()方法,由于重写了toString()方法所以的到的是这样的结果。

    5.

     

    由上图可以看到子类的对象可以赋值给父类对象,子类对象之间不可以相互赋值。

    虽然父类对象可以强制转化为子类对象并赋值给子类对象,没有报错,但是运行时会报错。

  • 相关阅读:
    47. Permutations II
    56. Merge Intervals
    57. Insert Interval
    常见算法问题
    67. Unique Paths
    版权声明
    121. Best Time to Buy and Sell Stock
    Leetcode backtracking 合集
    转载 int和string 类型的互换
    prim算法,克鲁斯卡尔算法---最小生成树
  • 原文地址:https://www.cnblogs.com/fengchuiguobanxia/p/13853212.html
Copyright © 2011-2022 走看看