java-继承构造方法?

Python019

java-继承构造方法?,第1张

class Goods {

double unitPrice//单价

double account//数量

Goods(double unitPrice, double account){

this.unitPrice = unitPrice

this.account = account

}

double totalPrice(){//计算总价

return unitPrice*account

}

void show(){

System.out.println("单价:"+unitPrice)

System.out.println("购买数量:"+account)

System.out.println("购买商品的总金额:"+this.totalPrice())

}

}

class Clothing extends Goods{

String style//样式

Clothing(String style, double unitPrice, double account) {

super(unitPrice, account)

this.style = style

}

void show(){

System.out.println("衣服单价:"+unitPrice)

System.out.println("衣服数量:"+account)

System.out.println("衣服总金额:"+this.totalPrice())

}

void showClothing(){

System.out.println("衣服样式:"+style)

this.show()

}

}

public class Prog1{

public static void main(String[] args) {

Clothing clothing = new Clothing("蓝色风衣",100,2)

clothing.showClothing()

}

}

java继承中对构造函数是不继承的,只是调用(隐式或显式)。

举例说明:

public class FatherClass {

public FatherClass() {

System.out.println(100)

}

public FatherClass(int age) {

System.out.println(age)

}

}

public class SonClass extends FatherClass{

public SonClass() {

}

public SonClass(int c) {

System.out.println(1234)

}

public static void main(String[] args) {

SonClass s = new SonClass(66)

}

}

编译后执行结果如下:

分析:SonClass s = new SonClass(66)

执行这句时,调用

public SonClass(int c) {

System.out.println(1234)//系统会自动先调用父类的无参构造函数(super())

}

在这个构造函数中,等价于

public SonClass(int c) {

super()//必须是第1行,否则不能编译

System.out.println(1234)

}

所以结果是100 1234

在创建子类的对象时,Java虚拟机首先执行父类的构造方法,然后再执行子类的构造方法。在多级继承的情况下,将从继承树的最上层的父类开始,依次执行各个类的构造方法,这可以保证子类对象从所有直接或间接父类中继承的实例变量都被正确地初始化。

3.如果子类构造函数是这样写的

public SonClass(int c) {

super(22)//必须是第1行,否则不能编译

//显式调用了super后,系统就不再调用无参的super()了

System.out.println(1234)

}

执行结果是 22

1234

总结1:构造函数不能继承,只是调用而已。

如果父类没有无参构造函数

创建子类时,不能编译,除非在构造函数代码体中第一行,必须是第一行显式调用父类有参构造函数

如下:

SonClass (){

super(777)//显示调用父类有参构造函数

System.out.println(66)

}

如果不显示调用父类有参构造函数,系统会默认调用父类无参构造函数super()

但是父类中没有无参构造函数,那它不是不能调用了。所以编译就无法通过了。

总结2:创建有参构造函数后,系统就不再有默认无参构造函数。

如果没有任何构造函数,系统会默认有一个无参构造函数。

是的,子类将继承父类的非私有的属性和方法。

在JAVA中,子类继承父类的所有方法和属性(构造方法要用关键super([参数])调用);继承是JAVA中一个重要的特色,便于程序的编写,提高代码的重用性。

1、如果给子类i提供get和set通过get调用的自然是子类的。

2、如果给父类和子类分别提供get和set,调的仍然是子类的,因为方法被重写。

扩展资料

在继承中用到super调用父类的构造

privateStringname

privateStringsex

publicxinxin1(Stringname,Stringsex)

{

this.name=name

this.sex=sex

}

publicvoidhello(){

System.out.println(“嗨!我是”+name+”我是”+sex+”孩”)

}