<< Chapter < Page | Chapter >> Page > |
What output is produced by the program shown in Listing 10 ?
Listing 10 . Listing for Question 10. |
---|
public class Ap099{
public static void main(String args[]){new Worker().makeObj();
}//end main()}//end class definition
class Worker{public void makeObj(){
NewClass obj = new NewClass(5);obj.x = 10;
System.out.println(obj.x);}//end makeObj()
}// end classclass NewClass{
private int x = 2;public NewClass(){}//end constructorpublic NewClass(int x){
this.x = x;}//end constructorpublic void setX(int x){
this.x = x;}//end setX()
public int getX(){return x;
}//end getX()}//end NewClass |
I recommend that you open another copy of this document in a separate browser window and use the following links to easilyfind and view the listings while you are reading about them.
This section contains a variety of miscellaneous information.
Financial : Although the Connexions site makes it possible for you to download aPDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, youshould be aware that some of the HTML elements in this module may not translate well into PDF.
I also want you to know that, I receive no financial compensationfrom the Connexions website even if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale onAmazon.com showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If youpurchase such a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it was made andpublished without my prior knowledge.
Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.
A. Compiler Error
Variables declared private really are private
The code in the following fragment attempts to ignore the setter and getter methods and directly access the private instance variable named x in the object referred to by the reference variable named obj .
obj.x = 10;
System.out.println(obj.x);
This produces a compiler error. The compiler error produced by JDK 1.3 is reproduced below.
Ap099.java:19: x has private access in
NewClassobj.x = 10;
^Ap099.java:20: x has private access in
NewClassSystem.out.println(obj.x);
^
Notification Switch
Would you like to follow the 'Object-oriented programming (oop) with java' conversation and receive update notifications?