Java程序初始化过程中方法覆盖问题
2007-10-04 20:02
513 查看
代码如下:
/**//*
* Test.java
*
* Created on 2007-10-4, 19:32:43
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/** *//**
*
* @author Jeffery
*/
class Base ...{
int i;
Base() ...{
add(1);
System.out.println("Base" + this.i);
}
void add(int i) ...{
this.i += i;
System.out.println("Base add i" + this.i);
}
}
class MyBase extends Base ...{
MyBase() ...{
add(2);
System.out.println("Mybase" + this.i);
}
void add(int i) ...{
this.i += i * 2;
System.out.println("Mybase add i" + this.i);
}
}
public class Test ...{
public static void main(String[] args) ...{
go(new MyBase());
}
static void go(Base b) ...{
b.add(8);
}
}
最后输出i的值为22
分析:按照之前一篇文章总结在主函数中,首先执行new MyBase(),在这个过程中,子类会首先调用父类的构造函数Base(),但Base()函数执行add()方法时特别需要注意, 这个add方法由于是在新建MyBase对象时调用的,所以将会首先查找MyBase类中是否有此方法。所以Base函数中的add(1)实际上是执行的乘2的方法。
/**//*
* Test.java
*
* Created on 2007-10-4, 19:32:43
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/** *//**
*
* @author Jeffery
*/
class Base ...{
int i;
Base() ...{
add(1);
System.out.println("Base" + this.i);
}
void add(int i) ...{
this.i += i;
System.out.println("Base add i" + this.i);
}
}
class MyBase extends Base ...{
MyBase() ...{
add(2);
System.out.println("Mybase" + this.i);
}
void add(int i) ...{
this.i += i * 2;
System.out.println("Mybase add i" + this.i);
}
}
public class Test ...{
public static void main(String[] args) ...{
go(new MyBase());
}
static void go(Base b) ...{
b.add(8);
}
}
最后输出i的值为22
分析:按照之前一篇文章总结在主函数中,首先执行new MyBase(),在这个过程中,子类会首先调用父类的构造函数Base(),但Base()函数执行add()方法时特别需要注意, 这个add方法由于是在新建MyBase对象时调用的,所以将会首先查找MyBase类中是否有此方法。所以Base函数中的add(1)实际上是执行的乘2的方法。
相关文章推荐
- java 程序加载过程---3--类中申明同时申明类的静态对象 创建类的实例 访问类的静态变量 调用类的静态方法 使用反射方法 初始化类的子类对象 直接使用java.exe 调用某个类
- 从父类构造器调用子类覆盖方法看Java初始化过程
- java 带有exception的父类方法覆盖问题
- Swing 写的客户端程序在java web start 运行,多语言过程中,JOptionPane.showMessageDialog() 按钮多语言问题
- Java 程序初始化过程详解 -转
- Java中方法和变量在继承时的覆盖问题
- 在Dos命令行下编译Java程序问题和解决方法集锦
- 一个Java方法覆盖的小问题
- java开发过程中对于乱码问题的解决方法
- 正试图在 os 加载程序锁内执行托管代码。不要尝试在 DllMain 或映像初始化函数内运行托管代码,这样做会导致应用程序挂起。问题的解决方法!
- 解析 Java 类和对象的初始化过程(由一个单态模式引出的问题谈起)
- 关于“socket:<10106> 无法加载或初始化请求的服务提供程序”问题的解决方法
- Java中static方法、程序入口函数main方法的继承问题
- 在eclipse中JAVA从打包成jar程序到双击运行的整个过程(没有主清单属性问题的解决)
- 一道Java程序输出题(继承-重载-覆盖-向上转型的问题)
- jpcap 配置方法,问题解决,模拟sniffer程序。(附JAVA程序,jar,dll包等环境)
- java ArrayList add()方法数据被覆盖问题
- 嵌入式软件开发培训笔记——Java第三天(方法重载、对象的构造与初始化过程分析、封装等)
- java程序调用存储过程得到新增加记录的id号的方法
- java 小程序查看器 启动:未初始化小程序 解决方法