zoukankan      html  css  js  c++  java
  • Java中的隐藏和覆盖(编译时类型和运行时类型)

    Java的引用变量有两个类型,一个是编译时类型,一个是运行时类型

    编译时类型:由声明该变量时使用的类型决定

    运行时类型:由该变量指向的对象类型决定  

    关于继承

    一个类一般包含有 静态方法,一般方法,  静态属性,一般属性这四类,  在继承关系中都会被子类继承到,但是只有一般方法可以被重写,从而具有多态性,其他三个都是被继承或被隐藏

    如果被隐藏了,那么访问的就是子类中的属性,而不管是不是合理。

    示例如下: 

    public class Test {
        public static void main(String[] args)  {
            Circle circle = new Circle();//本类引用指向本类对象   
          //运行结果是
     
                //shape constructor
                //circle constructor

    Shape shape = new Circle();//父类引用指向子类对象(会有隐藏和覆盖)
           
    //运行结果是
               //shape constructor
               //circle constructor

           System.out.println(circle.name);
           circle.printType();
           circle.printName();
           //以上都是调用Circle类的方法和引用\
          //运行结果是
              //
    circle
              //this is circle
              //circle
            System.out.println(shape.name);//调用父类被隐藏的name属性
            shape.printType();//调用子类printType的方法
            shape.printName();//调用父类隐藏的printName方法 
            //运行结果是

                     //shape
                    //this is circle
                    //shape


    } } class Shape { public String name = "shape"; public Shape(){ System.out.println("shape constructor"); } public void printType() { System.out.println("this is shape"); } public static void printName() { System.out.println("shape"); } } class Circle extends Shape { public String name = "circle"; //父类属性被隐藏 public Circle() { System.out.println("circle constructor"); } //对父类实例方法的覆盖 public void printType() { System.out.println("this is circle"); } //对父类静态方法的隐藏 public static void printName() { System.out.println("circle"); } }
  • 相关阅读:
    使用 asp.net mvc和 jQuery UI 控件包
    ServiceStack.Redis 使用教程
    HTC T8878刷机手册
    Entity Framework CodeFirst 文章汇集
    2011年Mono发展历程
    日志管理实用程序LogExpert
    使用 NuGet 管理项目库
    WCF 4.0路由服务Routing Service
    精进不休 .NET 4.0 (1) asp.net 4.0 新特性之web.config的改进, ViewStateMode, ClientIDMode, EnablePersistedSelection, 控件的其它一些改进
    精进不休 .NET 4.0 (7) ADO.NET Entity Framework 4.0 新特性
  • 原文地址:https://www.cnblogs.com/djma/p/14970454.html
Copyright © 2011-2022 走看看