Syntax for 'new' in java [duplicate]
Asked Answered
F

3

7

Constructors of non static member classes take an extra hidden parameter which is a reference to an instance of the immediately enclosing class. There is also a syntactic extension of 'new'.

In the below code,

class K{
    static class Ka{
        static class Kb{
            class Kc{
                class Kd{

                }
            }
        }
    }
}

class Test{
    K.Ka.Kb.Kc.Kd k = new K.Ka.Kb().new Kc().new Kd();
}

Can you please help me understand the meaning of Kb() in K.Ka.Kb().new Kc().new Kd()? I understand that new Kc() is required as told in first paragraph.

Finalist answered 8/9, 2015 at 14:31 Comment(1)
only if you bothered reading thisPharmacopoeia
C
3

It's calling the constructor of Kb. It's easier to show this in three statements:

K.Ka.Kb x1 = new K.Ka.Kb();
K.Ka.Kb.Kc x2 = x1.new Kc(); // Pass x1 as the hidden constructor arg
K.Ka.Kb.Kd.Kd k = x2.new Kd(); // Pass x2 as the hidden constructor arg
Converge answered 8/9, 2015 at 14:37 Comment(0)
U
7

The parentheses you point out actually do not apply to Kb but K.Ka.Kb.

new K.Ka.Kb()

is creating a new instance of the K.Ka.Kb nested class.

Uterus answered 8/9, 2015 at 14:36 Comment(3)
Oh you mean (new K.Ka.Kb()).new Kc().new Kd();?Finalist
@SotiriosDelimanolis kc and kd are inner class. But the idiom of saying non static member class as inner class, is it a standard jargon?Finalist
YesEllissa
C
3

It's calling the constructor of Kb. It's easier to show this in three statements:

K.Ka.Kb x1 = new K.Ka.Kb();
K.Ka.Kb.Kc x2 = x1.new Kc(); // Pass x1 as the hidden constructor arg
K.Ka.Kb.Kd.Kd k = x2.new Kd(); // Pass x2 as the hidden constructor arg
Converge answered 8/9, 2015 at 14:37 Comment(0)
C
1

Kb() is the default constructor for class Kb. It is what relates to the first new of the line:

  1. you are creating a new instance of Kb (class K.Ka.Kb actually ; depending on the context you may omit K.Ka.)
  2. on which you are calling new Kc() for creating a new instance of Kc
  3. on which you are calling new Kd() for creating a new instance of Kd
Constringent answered 8/9, 2015 at 14:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.