构造函数的顺序在Java中调用super()

时间:2015-10-31 20:48:31

标签: java constructor

我试图解释为什么这段代码没有返回我期望的内容:

  def extract_increasing_groups(seq):
    seq = tuple(seq)

    def is_increasing(a,b):
        return a + 1 == b

    def unzip(seq):
        return tuple(sorted({ y for x in zip(*seq) for y in x}))

    group = []
    for a,b in zip(seq[:-1],seq[1:]):
        if is_increasing(a,b):
            group.append((a,b))
        elif group:
            yield unzip(group)
            group = []

    if group:
        yield unzip(group)

if __name__ == '__main__':

    x = [17, 17, 19, 20, 21, 22, 0, 1, 2, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12,

         13, 14, 14, 14, 28, 29, 30, 31, 32, 33, 34, 35, 36, 40]

    for group in extract_increasing_groups(x):
        print(group)

返回

from collections import namedtuple
from itertools import islice, tee

def extract_increasing_groups(iterable):

    iter1, iter2 = tee(iterable)
    iter2 = islice(iter2,1,None)

    is_increasing = lambda a,b: a + 1 == b
    Igroup = namedtuple('Igroup','group, len')

    group = set()
    for pair in zip(iter1, iter2):
        if is_increasing(*pair):
            group.update(pair)
        elif group:
            yield Igroup(tuple(sorted(group)),len(group))
            group = set()

    if group:
        yield Igroup(tuple(sorted(group)), len(group))


if __name__ == '__main__':

    x = [17, 17, 19, 20, 21, 22, 0, 1, 2, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14, 14, 28, 29, 30, 31, 32, 33, 34, 35, 36, 40]
    total = 0
    for group in extract_increasing_groups(x):
        total += group.len
        print('Group: {}\nLength: {}'.format(group.group, group.len))
    print('Total: {}'.format(total))

我希望public class Bike { int height; int color; public Bike(int height, int color) { this.height = height; this.color = color; } } public class MountainBike extends Bike { public MountainBike(int height, int color) { super(height, color); super.height = 200; System.out.println(super.height); System.out.println(height); } } public class Main { public static void main(String[] args) { MountainBike a = new MountainBike(1, 1); } } 打印出200 1 ,而只打印超级电话。

操作顺序为:

0。 System.out.println(height)

1。 200

2。 all fields including superclass fields are declared and memory is allocated

3。 super() call from MountainBike constructor is called

4。 super() call from Bike constructor is called

5。 Object super() call is called

6。 Bike fields are initialized (nothing happens in this case)

7。 Bike constructor is executed (height and color are set to arguments from the super() call from MountainBike)

在这种情况下,有人可以指出我的错误吗?

2 个答案:

答案 0 :(得分:2)

System.out.println(height);构造函数中的MountainBike正在打印传递给构造函数的参数的值,即1.面对多个具有相同名称的变量,Java将使用"最接近"在范围内。

答案 1 :(得分:1)

你在做什么与构造函数的顺序无关。

您通过参数“隐藏”了字段高度。 现在您正在更新字段而只更新字段。

您打印字段,然后打印参数,该参数仍然是传递给构造函数的原始值。

顺便说一下:首先执行Bike的构造函数。

相关问题