JAVAsuper

父类有一个无参数的构造方法, 当实例化一个子类之后, 其构造方法也会被调用, 其父类的构造方法也会被调用, 并且父类的构造方法会先被调用, 子类构造方法会默认调用父类的构造方法.

	public class AA{
		public AA(){
			System.out.println("父类构造方法");
		}
	}
	
	public class BB extends AA{
		public BB(){
			System.out.println("子类构造方法");
		}
	}

	public static void main(String[] args) {
        new AA ();  //输出: 父类构造方法
        new BB();  //输出: 父类构造方法
    }

使用super调用父类构造方法

	public class AA{
		public int i = 0;
		public AA(){
			System.out.println("父类构造方法");
		}
		public AA(int i){
			this.i = i;
			System.out.println("父类构造方法"+this.i);
		}
	}
	
	public class BB extends AA{
		public int i = 0;
		public BB(int i){
			super(i);
			System.out.println("子类构造方法");
		}

	public static void main(String[] args) {
        new BB(233);  
    }
    //输出: 父类构造方法233
    //		子类构造方法

先调用了父类的构造方法, 然后又调用了子类的构造方法.

super调用父类属性值

	public class AA{
		public int i = 0;
	}

	public class BB extends AA{
		public int i = 10;
		public int geti(){
        return this.i;
    }
    public int getfatheri(){
        return super.i;
    }
	}

	public static void main(String[] args) {
       BB b = new BB();  
       System.out.println( b.geti());       // 10
       System.out.println( b.getfatheri()); // 0
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值