initialize Class- consturctors

本文探讨了Java中从基类构造派生类对象的过程,包括不同构造函数的使用及如何通过super关键字调用基类构造函数。展示了当派生类构造函数未显式调用基类构造函数时,默认行为及其可能引发的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

package com.eric.object;

public class ConsturctsFromBaseClass {
 public static void main(String args[]) {
  DerivedClass dc=new DerivedClass();
  DerivedClass dc2=new DerivedClass("Eric");
  DerivedClass dc3=new DerivedClass(5);
 }
}

class BaseClass {
 public int i;
 
 public BaseClass() {
  System.out.println("base class no parameter construct!");
 }
 
 public BaseClass(int i) {
  this.i = i;
  System.out.println("base class parameter constructor output!");
 }
}

class DerivedClass extends BaseClass {
 // public DerivedClass(){
 //
 // }
 /**
  * if don't call super construct from Base class, it's will call default
  * construct from BaseClass, if in BaseClass just have been define parameter
  * construct, the complier will complain that  can't find a default construct
  * of the form BaseClass()
  **/
 public DerivedClass(int i) {
  super(i);
  System.out.println("Derived output....");
 }
 public DerivedClass(String name){
  System.out.println("parameter is String Derived output.....");
 }
 public DerivedClass(){
  System.out.println("empty parameter derived class constructor output....");
 }
 
 
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值