• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

OCJP Polmorphism on variabels

 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey all,
Given below code...

package Test1;

public class superma {
protected int g=9;
}


package Set2;
import Test1.superma;

public class Q37 extends superma {
//int g=12; //Global scope
public static void main(String args[])

{
//int g=12; //Local scope
Q37 a= new Q37();
//superma m= new superma();
System.out.println(a.g);
}
private void fogo(){}
}


If the variable g is declared in Q37 as local variable it prints the value of superma.g i.e 9 but when its is declared as global variable it prints 12.Please explain
Thanks
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Please QuoteYourSources.

Henry
 
ali kamran
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Henry Wong wrote:
Please QuoteYourSources.

Henry



Hi Again,
This is totally from me while revising Kathy Sierra book Page 38 and mixing page 37 and 35.Please state any issue ?

 
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The variable you print a.g is the instance variable of the class Q37. If the variable g is not defined (which you have marked as global scope), the variable g is inherited from its super class superma. If it's defined then the global scope variable's value is printed.

The definition of local scope g has no effect on the outcome.
 
What is that? Is that a mongol hoarde? Can we fend them off with this tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic