• java继承时候类的运行顺序问题


    子类在继承父类后,创建子类对象会首先调用父类的构造函数,先运行父类的构造函数,然后再运行子类的构造函数,例如以下所看到的:


    class Father{
    	public Father(){
    		System.out.println("I am father");
    	}
    }
    public class Child extends Father{
    	public Child(){	
    		System.out.println("I am child");
    	}
    	public static void main(String[] args) {
    		Father f=new Father();
    		Child c=new Child();
    	}
    }

    当父类有带參数的构造函数时,子类默认是调用不带參数的构造函数,例如以下所看到的:


    class Father{
    	public Father(){
    		System.out.println("I am father");
    	}
    	public Father(String name){
    		System.out.println("I am father,My name is "+name);
    	}
    }
    public class Child extends Father{
    	public Child(){	
    		System.out.println("I am child");
    	}
    	public static void main(String[] args) {
    		Father f=new Father("Apache");
    		Child c=new Child();
    	}
    }

    若想子类调用父类带參数的构造函数,须要用super()函数申明,例如以下:

    class Father{
    	public Father(){
    		System.out.println("I am father");
    	}
    	public Father(String name){
    		System.out.println("I am father,My name is "+name);
    	}
    }
    public class Child extends Father{
    	public Child(){	
    		super("Apache");
    		System.out.println("I am child");
    	}
    	public static void main(String[] args) {
    		Father f=new Father("Apache");
    		Child c=new Child();
    	}
    }


  • 相关阅读:
    向MyEclipse添加Oracle数据库
    如何让搜索引擎抓取AJAX内容?
    XCode常用快捷键
    VMware Workstation 9上安装Mac OS X 10.8
    IOS学习第一篇——利用Xcode中的Interface Builder创建Hello World示例
    FM 101.7
    SqlServer游标操作
    添加COOKIE
    c#活动目录操作
    WCF服务调用方式
  • 原文地址:https://www.cnblogs.com/hrhguanli/p/3777254.html
Copyright © 2020-2023  润新知