zoukankan      html  css  js  c++  java
  • java中子类与父类中隐含的this引用的分析

    /*
        看一下下面的程序,看是否你的答案和运行的答案是否一致!
    */
    class Parent{
         
        public int x;
        public Parent p;
         public Parent(){}
         public Parent(int x){
               this.x=x; 
               p=this;
        }
        
         public void f(){
                System.out.println("Parent::f()"); 
         }
            
          public void g(){
                System.out.println("Parent::g()");
         }
        
         public void h(){
                System.out.println("Parent::h()");
                f();
                g();
                y();
                System.out.println("LOOK HERE: " + x);
         }
            
         private void y(){
                System.out.println("Parent::y()");
         }
    };
    
    class Child extends Parent{
        public int x;
            
        public Child(){}
        public Child(int x){ 
                super(x+5);
                this.x=x;
        }
        
        public void f(){
                System.out.println("Child f()");
        }
        
        public void g(){
                System.out.println("Child g()"); 
        }
    };
    
    
    public class ThisDemo {
    
        public static void main(String[] args) {
                Child ch=new Child();
                ch.h();
                System.out.println();
                ch=new Child(5);
                ch.h();
                System.out.println();
                ch.p.h();
        }
    
    }
    
    其实c++this思想和java中的this思想差不多,就是在多态的情况下有一些不同,c++基类中的方法如果没有有virtual修饰,那么派生类的重写该方法时就不是覆盖,不会具有包含多态(c++多态的种类:强制多态、重载多态、类型参数化多态、包含多态(就是通过用virtual))!然而在java中,如果子类中重写了父类的方法,那么就是覆盖,就会产生像c++使用virtual的多态!
    
    c++样例请点击这里:here
    输出结果:
    /*
    Parent::h()
    Child f()
    Child g()
    Parent::y()
    LOOK HERE: 0
    
    Parent::h()
    Child f()
    Child g()
    Parent::y()
    LOOK HERE: 10//输出的是父类中的x
    
    Parent::h()
    Child f()
    Child g()
    Parent::y()
    LOOK HERE: 10//输出的是父类中的x
    */
     
  • 相关阅读:
    【NIO】NIO之浅谈内存映射文件原理与DirectMemory
    【搜索引擎】全文索引数据结构和算法
    【多线程】并发与并行
    【缓存】缓存穿透、缓存雪崩、key重建方案
    布隆过滤器
    多层路由器通信
    【路由】设置二级路由器
    【硬件】集线器,交换机,路由器
    JZOJ100048 【NOIP2017提高A组模拟7.14】紧急撤离
    JZOJ100045 【NOIP2017提高A组模拟7.13】好数
  • 原文地址:https://www.cnblogs.com/hujunzheng/p/3963487.html
Copyright © 2011-2022 走看看