zoukankan      html  css  js  c++  java
  • JAVA多态的理解

    //看如下代码:

    package thinking.in.java;
    public class PrivateOverride {
        private void f(){
            System.out.println("private f()");
        }
        private void ss()
        {
            System.out.println("this is a base class private method");
        }
        public void se()
        {
            System.out.println("this is a base class public method");
        }
        public final void sf()
        {
            System.out.println("this is a base class final method");
        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
                PrivateOverride po=new Derived();
                po.f();
                po.ss();
                po.se();
                po.sf();
                ((Derived) po).sp();
                
                Derived dd=    new Derived();
                dd.f();
                dd.sp();
                dd.se();
                dd.sf();
        }
    
    }
    class Derived extends PrivateOverride{
        public void f(){
            System.out.println("public f()");
        }
        public void sp(){
            System.out.println("Base Class don't have");
        }
    }

    //输出结果为:

    private f()

    this is a base class private method

    this is a base class public method

    this is a base class final method

    Base Class don't have

    public f()

    Base Class don't have

    this is a base class public method

    this is a base class final method

    解析:由于private方法是final方法,而且对于子类是屏蔽的,因此,Derived类中的f()方法就

    是一个全新的方法,既然基类中的方法在子类中不可见,因此也不能重载。由程序执行结果来看

    ,将基类引用指向子类对象后,基类引用可以访问基类独有的和不能被子类覆盖的方法(即

    private,final,还有部分子类没有覆盖的),访问子类已经覆盖的方法时,执行的是子类中的

    该方法。若要执行子类中特有的方法,就得将该引用强制转换为子类引用(如:((Drieved)

    op).sp()),当定义子类引用指向子类对象后,则只能访问子类继承的(除屏蔽的private方法外

    )和其有的方法。可见final方法只是不能被子类覆盖(我亲自试了,不能覆盖),但是可以被

    子类继承

  • 相关阅读:
    前端开发中同步和异步的区别
    SQL STUFF函数 拼接字符串
    Javascript的精华
    .net网站报错:对象的当前状态使该操作无效
    免费 WebOffice使用
    DotNetBar教程
    C#获取周的第一天、最后一天、月第一天和最后一天
    C#判断文字是否为汉字
    C# 将字符串转为ऩ这种的 html实体编码
    SqlServer将没有log文件的数据库文件附加到服务器中
  • 原文地址:https://www.cnblogs.com/ylgl/p/3861941.html
Copyright © 2011-2022 走看看