<< Chapter < Page | Chapter >> Page > |
(The name of this method complies with JavaBeans design patterns. If you examine the name carefully, you will see why Java programmers often refer tomethods like this as getter methods.)
public int getX(){
return x;}//end getX()
Calling the getter method
Finally, the second statement in the following code fragment calls the getter method on the NewClass object to get and display the value of the instance variable named x .
NewClass obj = new NewClass(5);
System.out.println(obj.getX());
C. Object containing 0, 0.0, false
Default initialization values
The purpose of this question is to confirm that you understand the default initialization of instance variables in an object when you don't write code tocause the initialization of the instance variable to differ from the default.
By default, all instance variables in a new object are initialized with default values if you don't provide a constructor (or other mechanism) that causes them to be initialized differently from the default.
C. Object containing 5
A parameterized constructor
This program illustrates the straightforward use of a parameterized constructor.
The class named NewClass defines a parameterized constructor that requires an incoming parameter of type int .
(For good design practice, the class also defines a noarg constructor, even though it isn't actually used in this program. This makes it available ifneeded later when someone extends the class.)
Both constructors are shown in the following code fragment.
public NewClass(){
}//end constructorpublic NewClass(int x){
this.x = x;}//end constructor
The parameterized constructor stores its incoming parameter named x in an instance variable of the class, also named x .
(The use of the keyword this is required in this case to eliminate the ambiguity of having a local parameter with the same name as aninstance variable. This is very common Java programming style that you should recognize and understand.)
Call the parameterized constructor
The following code fragment calls the parameterized constructor, passing the literal int value of 5 as a parameter.
NewClass obj = new NewClass(5);
Hopefully you will have no difficulty understanding the remaining code in the program that causes the value stored in the instance variable named x to be displayed on the computer screen.
A. Compiler Error
If you define any constructors, ...
Notification Switch
Would you like to follow the 'Object-oriented programming (oop) with java' conversation and receive update notifications?