• 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
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

emergency service required

 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This may be a silly question.But for me without this i can't move forward.
So this is the program;
I)class Base{int i =20;}
class Derived extends Base
{
Derived()
{
int i = 30;
System.out.print(i);
}
public static void main(String args[])
{
Derived d = new Derived();
System.out.print(d.i);
}
}
ans: 25 30 25

1)something called overloding of fields here?
2)how I can declare i without identifier at Derived()
constructor?
3)if I declare as int i why result is different?
4)why only at constructor, I can declare i without
identifier?
If question not clear please point out
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First the output is 30 20
and not 25 30 25 (you have only two println)
this is not overloading of fields but hiding, since in the constructor Derived() you have a local variable i which hides the member i inherited from Base. Then in the main the inherited i is printed.

------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
[This message has been edited by Valentin Crettaz (edited October 02, 2001).]
 
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Jyothi,
1. Only methods can be 'overloaded'. The term doesn't apply to fields.
2. To initialize 'i' in Derived you can use

'i' is inherited from 'Base', you don't need to re-create it.
3. When declare 'int i' in the Derived constructor you are creating a 'local variable'. It can only be seen within the constructor.
4. You could use 'i' in another method in Derived without declaring it. See below:

The output is:

Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
jyothi abraham
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thank you to JANE and VALENTINE for taking pains to answer
eventhough qustion was not clear,
JYOTHI ABRAHAM
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi jyoti ,
here is something more interesting add to your code..
class Base{int i =20;}
class Derived extends Base
{
Derived()
{
i=35;//new code added
int i = 30;
System.out.print(i);
}
public static void main(String args[])
{
Derived d = new Derived();
System.out.print(d.i);
}
}
answer is 30 35
But i am just wondering can I have a local variable with the same name as the instance variable ..
regards
royce
 
royce abraham
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi jyoti
some thing more interesting
class Base{int i =20;}
class Derived extends Base
{
Derived()
{
i=35;
int i = 30;
System.out.print(i);
}
public static void main(String args[])
{
Derived d = new Derived();
System.out.print(d.i);
}
}
answer 3035
observation: it allows a local variable to have the same name as the instance variable and recognises it without an error.
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
>But i am just wondering can I have a local variable with the same name as the instance variable ..

Absolutely, but the local variable will cause the instance variable to be unseen while you are in the scope of the local variable. This is called "shadowing", I believe, (please correct me if my terminology is wrong). The only way to access the instance variable while you are in the scope of the local variable by the same name is by using the keyword "this".
 
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Marylin,


The only way to access the instance variable while you are in the scope of the local variable by the same name is by using the keyword "this".


This mean that we can use this in constructors?
Regards,
Hassan.
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Hassan,
Yes, you can use 'this' in constructors.

Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
arch rival
Posts: 2813
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think the word emergency should be reserved for emergency, just in case you ever have an emergency.
------------------

http://www.jchq.net Mock Exams, FAQ,
Tutorial, Links, Book reviews
Java 2 Exam Prep, 2nd Edition by Bill Brogden and Marcus Green
=================================================
Almost as good as JavaRanch
=================================================
 
jyothi abraham
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for advices.But in earlier letter I forgot to point out
this.My original program was this;
class Base
{
int i = 20;
}
class Derived extends Base
{
Derived()
{
int i =30;//*without identifier just i=30; noti=30what is o/p?
System.out.print(i);
}
public static void main(String args[])
{
Derived d = new Derived();
System.out.print(d.i);
}
}
ans:
i)(at *commented part-->int i=30; is) 25 30 25
ii)(at *commented part--> i = 30; is) 25 30 30
I know the first two part of answers of i) and ii) now from your answers.My doubt is now on the third part(for d.i = 25 and 30 on the third part of i)and ii))
Here I know these terms:
Hiding:If the class declares a field with a certain name,then the
declaration of that field is said to hide any and all of fields
with the same name in superclasses and superinterfaces of the class.
Shadowing:local variable (declared) will cause the instance variable to be unseen while you are in scope of local variable.
So when I tried to acess the value of i for the object(d) of class derived;
if I declare i =30; then as by hiding locally declared variable
(int i = 30; outside constructor) will hide the inherited i.so
I should get i = 25 at o/p.
if I declare int i = 30; then as by shadowing for constructor
locally described variable is int i = 30; rather than int i =25;
so we should get i=30 at o/p.
But as you see,o/p is reverse.I know somewhere in my explanation
there is a blunder.please help out.

 
jyothi abraham
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
sorry,again.I missed two lines in my small program again.Take
it easy,Guys.My actual program is;
class Base
{
int i = 20;
}
class Derived extends Base
{
Derived()
{
int i =30;//*without identifier just i=30; noti=30what is o/p?
System.out.print(i);
}
int i =25;{System.out.print(i);}//missed lines//
public static void main(String args[])
{
Derived d = new Derived();
System.out.print(d.i);
}
}
 
Hassan Naqvi
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jane.
 
jyothi abraham
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
please reply
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
jyothi,
I'm not sure what your asking???
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
Ranch Hand
Posts: 5399
1
Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Hi jyothi
even yesterday i get confused too.... and even mail to Jane.... sorry for bothering ..
but today i get the explanation.. while explaning your problem to jane(though I did not post that explanation)
but here is the explanation... correctme if i am wrong

java code is this:


<pre>
class Base {
int i = 20;
}

class Derived extends Base
{
Derived() {
//int i =30; // *1
i = 30; // *2
System.out.println( i );
}
int i =25;
{
System.out.println( i );
} //missed lines//

public static void main(String args[])
{
Derived d = new Derived();
System.out.println( d.i );
}
}
</pre>


case 1)when *1 is uncommented and *2 is commented-
i.e.
int i = 30;
// i = 30;
o/p is
25
30
25
because int i is auto variable it will hide member variable 'i' only for constructor block.
i) Now the first thing executed is annonymous block, when U create an object..
so u get printed '25'.
ii) After annonymous block, constructor is executed, and as you have 'shadowed' the mamber variable 'i', you get printed '30'
iii) now main()'s print statement is executed, and as i has a value of 25(constructor's i shadowed member variable i, i's value does not change), '25' get printed.
case 2)when *2 is uncommented and *1 is commented-
i.e.
// int i = 30;
i = 30;
o/p is
25
30
30
because
i) Now the first thing executed is annonymous block, when U create an object..
so u get printed '25'.
ii) After annonymous block, constructor is executed, and Key point is here that the 'i' we are using is not from base class , it is member variable of the same class(I think we were confused by the position of declaration of mamber variable i, we should keep in the mind that it is not auto variable, it is member variable and there position of declaration does not matter as we can declare and define(in java declaration and definition are written at the same place) member method even after using(calling) them.)
so we assign(not declare ) value of 30 to menber variable 'i' and get the same printed '30'

iii) now main()'s print statement is executed, and as i(member variable) has a value of 30(it is not changed since contstructor executed), '30' get printed.



Here there was only Shadowing not "Hiding"

I wish I can understand what i have written here after posting it.
All The Best
and if i am wrong then correct me.....
------------------
Regards
Ravish
[This message has been edited by ravish kumar (edited October 17, 2001).]
[This message has been edited by ravish kumar (edited October 17, 2001).]
 
jyothi abraham
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hai Ravish,
Thank you for your beautiful explanation.
Atleast my example helped me to clear shadowing.
Then what this hiding,please explain with detailed example.
If possible explain obscuring too.
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys,
Try this Sun Article. It explains shadowing, hiding and obscuring with examples.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
R K Singh
Ranch Hand
Posts: 5399
1
Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi jyothi
I try to explain ... but do go through jane's link, it is good and help you.
Shaodwing:
when in a class you over-write(this is my terminology...NO override, NO overload)any variable, you can do this by redeclaring the variable with same name in member methods(if u try in the class then u will get compile error as already defined variable..), then you are shadowing the already defined member variable.
To access the member variable you have to use the instance of the class, 'this' is available to you in the class, so you will access the member variable by using 'this.var' in the shadowed block or method.
So your local variable will over shadow member variable if they have same name.
In simple words shadowing is done in a (one)class, and in case of shadowing we use 'this' keyword.
Hiding:
You define some member variable/method in a class, when that class is extended then derive class can over-write already defined members of base class. when methods are over-written then this is called overriding. The methods which can not be overriden (static methods) or member varibles, if derived class has same declaration for either(static method or member varible) then it is said "hiding", as you are hiding the already defined member.
To access base class member when it is hided by derived class we use 'super' keyword.
In simple word hiding occurs when there is inheritence and we have to use 'super' for base members.
wish it will help you...
CMIW
now Que for Jane:
can u slightly elaborate obscure?
what i get that if we use variable name as already defined class name then it will create confusion to compiler .. and then to use class u should classify full name of class.
CMIW
------------------
Regards
Ravish

[This message has been edited by ravish kumar (edited October 25, 2001).]
 
jyothi abraham
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1)In RaVISH's reply, the shadowing part:we can't reinitialize a variable inside a class.but in method it is possible;
class Class{int i=5;i=10;//--->compilaton error
method(){int j = 5;j=10;}}
How this is?
2)If I put anything under '{}'block it will be considered as local in a "method".Why I am telling this is in an "initializer block "({})if I put any declarations it will be local only.But if I put any declarations it will be local only.But if I give values that is declared outside block it will be valid outside block also(then called initialization).
How this 'sitting in two boats at same time' possible for compiler to '{}'.
NB:I am not from hard programming.But I wish to know this clearly.
 
R K Singh
Ranch Hand
Posts: 5399
1
Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



1)In RaVISH's reply, the shadowing part:we can't reinitialize a variable inside a class.but in method it is possible;
class Class{int i=5;i=10;//--->compilaton error
method(){int j = 5;j=10;}}
How this is?


Hi Jyothi,
I said u can not redeclare (NOTE not reinitialize) a variable with same name in same block of statement.Whether that block is a class block or method block.(one block is space between two {} ).
I wanted to say :
class Class{int i=5; int i=10;//--->compilaton error
and
method(){int j = 5; int j=10;}}//--->compilaton error
BUT u can do this:
<pre>
class Class {
int i=5;
method() {
int i; // Shadwing of member varible 'i'
}
}
</pre>
even Java does not permit this
<pre>
{// outer block
int i = 0;
{// inner block
int i = 5;
}
}
</pre>
in C++ this is permitted (at least till Nov 98, it was permitted, I do not know what is going on with my exWife C++ now )
CMIW
Can u elaborate this, any example??


2)If I put anything under '{}'block it will be considered as local in a "method".Why I am telling this is in an "initializer block "({})if I put any declarations it will be local only.But if I put any declarations it will be local only.But if I give values that is declared outside block it will be valid outside block also(then called initialization).
How this 'sitting in two boats at same time' possible for compiler to '{}'.
NB:I am not from hard programming.But I wish to know this clearly.



------------------
Regards
Ravish
[This message has been edited by ravish kumar (edited October 25, 2001).]
[This message has been edited by ravish kumar (edited October 25, 2001).]
[This message has been edited by ravish kumar (edited October 25, 2001).]
 
jyothi abraham
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I will put my qusetions once again,now with examples;
(Now I am not asking about shadowing,simply reinitialization)
1)(Now I am not asking about shadowing,simply reinitialization)
class Class
{int i=5;
//i=10;--->compilaton error if I add this part."why?"
method()
{
int j = 5;
j=10;//inside method I can put same thing no errors. "why no errors"
}
}
How this is?why?
2)If I put anything under '{}'block it will be considered as local in
a "method".Why I am telling this is in an "initializer block "({})if
I put any declarations it will be local only.But if I put any
declarations it will be local only.But if I give values that is
declared outside block it will be valid outside block also
(then called initialization).
How this 'sitting in two boats at same time' possible for compiler to
'{}'.
eg:a)
class Doubt1//program started.
{
int a;
{
a=10;
int b = 5;
}
System.out.println(a);//I get a = 10.Then why can't I acess 'b'as
// shown below?

//System.out.println(b);--->error,I can't access b from here.This
//isjust like a method variable you can't access.
void method()
{
int c = 11;
}
//System.out.println(c);--->just like the case of 'b'.
}//program finished.
WHAT IS NOT POSSIBLE IN METHOD BLOCK IS POSSIBLE IN INITIALIZER BLOCK.
WHY?
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi jyothi,

You have to keep in mind that a 'class' is really a template used to create objects. It describes the data (fields) the object will hold and its behaviour (methods). The body of a class declaration is written in a {} block. It can legally contain:

  • field declarations with an optional initializer expressions
  • initialization blocks
  • method declarations
  • inner class declarations

  • <code>i = 10;</code> is an assignment statement and is illegal because of where it is placed.. The compiler doesn't know what to do with it. It's not a field declaration, a method, an inner class and it's not within an initialization block.
    The same statement causes no error within a method or an initialization block as assignment statements are legal within them.
    <pre>
    class Doubt1
    {
    int a; // field declaration
    {
    a=10; // assignment statement
    int b = 5; // local variable
    }
    System.out.println(a); //I get a = 10.
    //Because 'a' is a 'field', it's available
    // to the entire object

    // Then why can't I acess 'b'as shown below?
    //System.out.println(b);--->error,
    // I can't access b from here.This
    // is just like a method variable you can't access.
    // because 'b' is a 'local variable'
    // it is only available within the block of code in
    // which it is declared

    void method()
    {
    int c = 11; // local variable
    }
    //System.out.println(c);--->just like the case of 'b'.
    // because 'c' is also a 'local variable'
    // and can only be accessed within it's declaring block

    }
    </pre>
    A field belongs to the object. The scope of a field declaration is the object itself.
    A local variable is a temporary feature of the object. It only has meaning within the scope of the block in which it appears.
    In your example, you are telling the compiler/JVM that 'a' is important to the object. It won't be the right type of object if it doesn't have 'a'. But that 'b' is only important when the object is first created (in an initializtion block) and 'c' is only important when the object is involved in doing 'method'.
    Hope that helps.
    ------------------
    Jane Griscti
    Sun Certified Programmer for the Java� 2 Platform
    [This message has been edited by Jane Griscti (edited October 25, 2001).]
 
R K Singh
Ranch Hand
Posts: 5399
1
Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by jyothi abraham:
I will put my qusetions once again,now with examples;
(Now I am not asking about shadowing,simply reinitialization)
1)(Now I am not asking about shadowing,simply reinitialization)
<pre>
class Class{
int i=5;
//i=10;--->compilaton error if I add this part."why?"
method(){
int j = 5;
j=10;//inside method I can put same thing no errors. "why no errors"
}
}
</pre>
How this is?why?


Jane is right.... repeting him:
The body of a class declaration is written in a {} block. It can legally contain:
1.field declarations with an optional initializer expressions
2.initialization blocks
3.method declarations
4.inner class declarations


Originally posted by jyothi abraham:

2)If I put anything under '{}'block it will be considered as local in a "method".


local in that block, if that block is happen to be method then in a method.


Why I am telling this is in an "initializer block "({})if I put any declarations it will be local only.But if I put any declarations it will be local only.But if I give values that is declared outside block it will be valid outside block also(then called initialization).
How this 'sitting in two boats at same time' possible for compiler to
'{}'.
eg:a)
<PRE>
class Doubt1//program started.
{
int a;
{
a=10;
int b = 5;
}
System.out.println(a);//I get a = 10.Then why can't I acess 'b'as
// shown below?

//System.out.println(b);--->error,I can't access b from here.This
//isjust like a method variable you can't access.
void method()
{
int c = 11;
}
//System.out.println(c);--->just like the case of 'b'.
}//program finished.
<PRE>
WHAT IS NOT POSSIBLE IN METHOD BLOCK IS POSSIBLE IN INITIALIZER BLOCK.
WHY?


Did you try to compile this ???
System.out.println(a);//I get a = 10.Then why can't I acess 'b'as
you will never get a = 10 at the place u wrote that code.
as all executable code should either in side method or intialization block.
other queries must be quenched by Jane... hope
Really good explanation Jane.
------------------
Regards
Ravish
[This message has been edited by ravish kumar (edited October 29, 2001).]
 
Hey, sticks and stones baby. And maybe a wee mention of my stuff:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic