super()用法

#super()用法
##1.super()可以调用父类的构造方法。

import java.util.*;
//父类
public class Father
{
	int id;
   //无参构造
	public Father(){
		System.out.println("调用父类的构造方法");
   //有参构造
   //public Father(int id){
	//	System.out.println("调用"+id);
	//}
}
//子类
 class Son extends Father//继承
{
	public Son() {
      //这里其实有一个super();这个super()系统会默认加上,就
      //像你不写构造方法。系统会默认加上一个无参构造。
      //并且不写也只可调用无参构造。
      //如果不写super();且只写有参构造会报错。
		System.out.println("调用子类的构造方法");
	}

}
//测试类
 class Test01
{
	public static void main(String[] args)
	{
	Son son=new Son();
	}
}

super()用法_第1张图片

import java.util.*;
//父类
public class Father
{
	int id;
    public Father(int id){
		System.out.println("调用id");
	}
	//public Father(){
		//System.out.println("调用父类的构造方法");
	//}
}
//子类
 class Son extends Father//继承
{
	public Son() {
		System.out.println("调用子类的构造方法");
	}

}
//测试类
 class Test01
{
	public static void main(String[] args)
	{
	Son son=new Son();
	}
}

super()用法_第2张图片

public class Father
{
	int id;
    public Father(int id){
		System.out.println("调用id");
	}
	//public Father(){
		//System.out.println("调用父类的构造方法");
	//}
}
//子类
 class Son extends Father//继承
{
	public Son() {
         super(10000);
		System.out.println("调用子类的构造方法");
	}

}
//测试类
 class Test01
{
	public static void main(String[] args)
	{
	Son son=new Son();
	}
}

super()用法_第3张图片

##2.super()也可以访问父类的字段和方法

import java.util.*;
//父类
public class Father
{
	int id;//父亲的名字
}
//子类
 class Son extends Father//继承
{
   int id;//儿子的名字
	public Son(int fid,int cid) {
     super.id=fid;//通过super关键字来访问*父类*的id属性
     this.id=cid;//通过this关键字来访问*本类*的id属性
		System.out.println(super.id+this.id);
	}

}
//测试类
 class Test01
{
	public static void main(String[] args)
	{
	Son son=new Son(1000,100);
	}
}

super()用法_第4张图片

你可能感兴趣的:(java)