Win a copy of Zero to AI - A non-technical, hype-free guide to prospering in the AI era this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

variable overriding

 
Ranch Hand
Posts: 238
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
author
Posts: 23886
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
Greenhorn
Posts: 20
jQuery Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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



 
Nothing? Or something? Like this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic