• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

explain the static,constructor concept

 
ekta garg
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read the following code and please give me line by line explaination :

I have two questions here,
1)Is the static variable x visible to class Middle.
2)If not then how the Middle constructor is able to evaluate on the value of x variable, simply by invoking super().

Many Thanks,

class Top {
static int x = 1;
public Top() { x *= 3 ;}
}

class Middle extends Top {
public Middle() {x += 1; }
public static void main(String [] args) {
Middle m = new Middle();
System.out.println(x);
}
}
 
Pranav Bhatt
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes as your Middle class extends Top . Better post your doubts related to core java at SCJP forum( Programmer Certification (SCJP) ). you will get quick replies
 
Campbell Ritchie
Sheriff
Pie
Posts: 49379
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Disagree. The variable x is visible to the Middle class because they are both in the same package and x has package-private (or default) access.
Because you are saying "x" alone the Middle class won't compile. If you say "Top.x" or "import static Top.x;" then it will compile. You are not using super() but the compiler implies it, so x becomes . . . then . . .

Work the rest out for yourself.
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ekta,

Let me try to solve the problem:

STATIC BELONGS TO CLASS NOT OBJECT

I am sure you are agree with me..!!!

DEFAULT VARIABLE HAS PACKAGE LEVEL ACCESS

Agree again !!

MIDDLE INHERITS TOP

Agree..!!!

INHERITANCE CAUSE SUBCLASS TO ACCESS PUBLIC,PROTECTED,DEFAULT ATTRIBUTE OF SUPERCLASS

agree!!

conclusion:

public middle()
{
super();
x += 1;
}

super cause
x*= 3;
so x will be updated to 3, then middle as it has access to it make it 4,
main method since it is static so it can call all static things directly,
print the value of x

thanks!
sunny
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic