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
    */
     
  • 相关阅读:
    C语言ll作业01
    C语言寒假大作战04
    C语言寒假大作战03
    C语言寒假大作战02
    C语言寒假大作战01
    C语言I作业12—学期总结
    C语言I博客作业11
    C语言I博客作业10
    第三章预习笔记-运算方法和运算部件
    非数值数据的编码表示
  • 原文地址:https://www.cnblogs.com/hujunzheng/p/3963487.html
Copyright © 2011-2022 走看看