File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes variable overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "variable overriding" Watch "variable overriding" New topic
Author

variable overriding

Mathew Lee
Ranch Hand

Joined: Jun 08, 2009
Posts: 238
What will happen when you attempt to compile and run the following code?

public class MyField{
int i=99;
public static void main(String argv[]){
MyField m = new MyField();
m.amethod();
}

void amethod(){
int i;
System.out.println(i);
}

}
1) The value 99 will be output
2) The value 0 will be output
3) Compile time error
4) Run time error




I was reading above question from link
http://www.jchq.net/certkey/0405certkey.htm

did not understand it clearly.

cannot we override class level variables with method variables
Any ideas, resources,sample code,links, highly appreciated. thanks in advance.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18840
    
  40

cannot we override class level variables with method variables


Static variables (ie. class variables) can't be overridden. Local variables (ie. method variables) can't be overridden. In fact, variables of any kind can't be overridden.

Overriding is for methods. Specifically instance methods, where the method of the base class is accessible to the subclass.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Frankely Diaz
Greenhorn

Joined: Oct 09, 2009
Posts: 20

The variables can not be override, the behavior that allows named a inner variable as same as an outer variable is called shadowing.

That code doesn't compile because you are using a local variable without initialized it



 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: variable overriding