• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Variables and Methods?

 
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can anyone let me know what do we mean by the saying
"Variables are shadowed and Methods are Overriden" ?
If possible give me a few examples..
Sonir
 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Variable shadowing has to do with your understanding for scoping. If a class
declares a member variable, then it can be over-shadowed by a local variable
declared in a method with the same name.

See code sample below:

class Test {
static public void main(String[] arg) {
Foo a = new Foo();
System.out.println(a.i);
a.FromFn();
}
}
class Foo {
public int i=12;
void FromFn() {
int i=99;
System.out.println(i); // local (over-shadowed i)
System.out.println(this.i); // class i
}
}

Method overriding had to do with subclassing, if class B extends class A, a
method is said to be overridded if the method from class A is redeclared in
Class B having the same name, argument list and return type.
In the code sample below class B overrides the SayHi() method from class A

class Test {
static public void main(String[] arg) {
A a = new A();
B b = new B();
a.SayHi();
b.SayHi();
}
}
class A {
void SayHi() {
System.out.println("Hi from class A");
}
}
class B extends A {
void SayHi() {
System.out.println("Hi from class B");
}
}
 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To use the example below:

In the above code i(if you compile it you will see that the output is 'Class B method' and 6. A simple way to remember why this is the case is that the method called at runtime (line 2) is the one described by the reference not the 'type' (i.e. the reference creted at line 1 is for an object of class B even though the 'type' is of class A.
For shadowed variables this is different. The value of the variable at line 3 is determined at compile time by the type ( so the value 6 is printed to the command line and not 3 as you might expect ).
Hope this helps
 
reply
    Bookmark Topic Watch Topic
  • New Topic