wood burning stoves 2.0*
The moose likes Mock Exam Errata and the fly likes explain the static,constructor concept Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Mock Exam Errata
Bookmark "explain the static,constructor concept" Watch "explain the static,constructor concept" New topic
Author

explain the static,constructor concept

ekta garg
Greenhorn

Joined: Jan 03, 2008
Posts: 2
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

Joined: Mar 20, 2006
Posts: 284
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

Joined: Oct 13, 2005
Posts: 38036
    
  22
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.
Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

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


Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: explain the static,constructor concept
 
Similar Threads
final modifier in variable
final when used in constructor
Question Regarding class loading precedence.
about this(..)
Increment operator