I came across a question in which it was stated that, classes within the same package can directly access and change the public instance variables within these classes. So, i decided to just try it out as i wanted to see how exactly it is to be done. Below is the code i implemented -
I get the following error -
I'm finding difficult to solve the above error. I know its not that difficult, but need your expert help friends.
I want class Tte to access the String variable 'name' from the class Tt. Both the classes are placed in same package dd. I tried different ways as seen the commented lines in class Tte i.e the import statement but i am not able to understand how to do it. Can someone help me out please!
On compiling the code with your suggested changes it does not work and gives the error as follows-
The changed code as follows -
Kindly help me friends i tried with other ways too and am also looking into the problem.
I have a folder named "dd" in which i have placed the Tt.java and Tte.java source files.
And then i have compiled them as following - C:\Documents and Settings\User\Desktop>javac dd\Tt.java // compiles properly
C:\Documents and Settings\User\Desktop>javac dd\Tte.java // on compiling it shows 3 errors as shown above
From the above as you can see, i am compiling from my current directory-> Desktop
Am i compiling correctly , please correct me if i am wrong
Kancharla Madhu wrote:Your trying to access instance variable without actual object instance so Compilation Error! i.e
Do one of the following things.
1) Declare variable, name as static i.e.
2) Create Object instance and then invoke the variable name. i.e.
Thank you so much Madhu for your solution . Actually, i knew the first solution that you suggested with 'static' keyword but not about the second one. Thanks. Would you like to give some tips for the OCPJP certification exam.