수요일, 5월 1
Shadow

#010 Create Your Own Java Classes

Lab Exercises

 

Exercise 1: Create your own class

So far, you have dealt with a single class that contains main(..) method.  In this exercise, you are going to create multiple classes among which one class invokes another class – more precisely, a method in a class invokes a method of another class.

(1.1) Build and run an application that uses newly created StudentRecord class

0. Start the NetBeans IDE if you have not done so.
1. Create a NetBeans project

  • Select File from top-level menu and select New Project.
  • Observe that the New Project dialog box appears.
  • Select General under Categories section and Java Application under Projects section.
  • Click Next.
  • Under Name and Location pane, for the Project Name field, enter MyStudentRecordExampleProject.
  • For the Create Main Class field, enter StudentRecordExample.  (Figure-1.10 below)
  • Click Finish.


Figure-1.10: Create a new project

  • Observe that the MyStudentRecordExampleProject project node is created under Projects pane of the NetBeans IDE and IDE generated StudentRecordExample.java is displayed in the editor window of the IDE.
2. Write StudentRecord.java.

  • Right click MyStudentRecordExampleProject and select New->Java Class.

  • Observe that the Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter StudentRecord.  (Figure-1.11 below)
  • Click Finish.


Figure-1.11: Create StudentRecord.java

  • Observe that the IDE generated StudentRecord.java is displayed in the editor window.
  • Modify the IDE generated StudentRecord.java as shown in Code-1.12 below.   Study the code by paying special attention to the bold-fonted comments.
public class StudentRecord {

/** Creates a new instance of StudentRecord */
public StudentRecord() {
}

// Declare instance variables.
private String name;
private double mathGrade;
private double englishGrade;
private double scienceGrade;

// Declare static variables.
private static int studentCount = 0;

/**
* Returns the name of the student
*/
public String getName(){
return name;
}

/**
* Changes the name of the student
*/
public void setName(String temp ){
name =temp;
}

/**
* Computes the average of the english, math and science
* grades
*/
public double getAverage(){
double result =0;
result =(getMathGrade()+getEnglishGrade()+getScienceGrade() )/3;
return result;
}

/**
* Returns the number of instances of StudentRecords
*/
public static int getStudentCount(){
return studentCount;
}

/**
* Increases the number of instances of StudentRecords.
* This is a static method.
*/
public static void increaseStudentCount(){
studentCount++;
}

// Instance methods
public double getMathGrade() {
return mathGrade;
}

public void setMathGrade(double mathGrade) {
this.mathGrade = mathGrade;
}

public double getEnglishGrade() {
return englishGrade;
}

public void setEnglishGrade(double englishGrade) {
this.englishGrade = englishGrade;
}

public double getScienceGrade() {
return scienceGrade;
}

public void setScienceGrade(double scienceGrade) {
this.scienceGrade = scienceGrade;
}
}

Code-1.12: StudentRecord.java

3. Modify the IDE generated StudentRecordExample.java as shown in Code-1.13.

  • Study the code while paying special attention to the bold-fonted comments.
  • Observe that StudentRecordExample class uses StudentRecord class.
public class StudentRecordExample {

public static void main(String[] args) {

// Create an object instance of StudentRecord class.
StudentRecord annaRecord =new StudentRecord();

// Increament the studentCount by invoking a static method.
StudentRecord.increaseStudentCount();

// Create another object instance of StudentRecord class.
StudentRecord beahRecord =new StudentRecord();

// Increament the studentCount by invoking a static method.
StudentRecord.increaseStudentCount();

// Create the 3rd object instance of StudentRecord class.
StudentRecord crisRecord =new StudentRecord();

// Increament the studentCount by invoking a static method.
StudentRecord.increaseStudentCount();

// Set the names of the students.
annaRecord.setName(“Anna”);
beahRecord.setName(“Beah”);
crisRecord.setName(“Cris”);

// Print anna’s name.
System.out.println(“Name = ” + annaRecord.getName());

// Print number of students.
System.out.println(“Student Count = “+StudentRecord.getStudentCount());
}

}

Code-1.13: StudentRecordExample.java

4. Build and run the program

  • Right click MyStudentRecordExampleProject and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-1.12 below)
Name = Anna
Student Count = 3

Figure-1.12: Result of running the application

Solution: The solution to this exercise is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javacreateclass/samples/MyStudentRecordExampleProject.  You can just open and run it.

5. (For your own exercise) Do make changes as following and build and run the application.

  • Modify StudentRecordExample.java as following:
    • Create another StudentRecord object using new keyword, call it myOwnRecord
    • Call setName() method of the myOwnRecord object passing “myOwn” as the value to set
    • Display the name of the myOwnRecord object
    • Set Math grade of myOwnRecord object
    • Set English grade of  myOwnRecord object
    • Set Science grade of myOwnRecord object
    • Display the average grade of myOwnRecord object

Summary

In this exercise, you have learned how to create and use your own class called StudentRecord class using new keyword.

 

Exercise 2: Build and run Java applications that use static (class) variables and static methods

When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables.  Class variables are referenced by the class name itself, <Class-name>.<static-variable>.  For more information, please read Understanding Instance and Class Members section of the Java tutorial.

  1. Build and run an application that uses static variables (and instance variables)
  2. Build and run an application that uses static methods (and non-static methods)

(2.1) Build and run an application that uses static variables and instance variables

1. Create a NetBeans project

  • Select File from top-level menu and select New Project.
  • Observe that the New Project dialog box appears.
  • Select General under Categories section and Java Application under Projects section.
  • Click Next.
  • Under Name and Location pane, for the Project Name field, enter MyStaticVariablesExampleProject.
  • For the Create Main Class field, enter StaticVariablesExample.  (Figure-2.11 below)
  • Click Finish.

 


Figure-2.11:Create MyStaticVariablesProject project

  • Observe that the MyStaticVariablesExampleProject project node is created under Projects pane of the NetBeans IDE and IDE generated StaticVariablesExample.java is displayed in the editor window of the IDE.

2. Write Variables.java.

  • Right click MyStaticVariablesExampleProject and select New->Java Class.
  • Observe that the Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter Variables.  (Figure-2.12 below)
  • Click Finish.


Figure-2.12: Create Variables.java

  • Observe that the IDE generated Variables.java is displayed in the editor window.
  • Modify the IDE generated Variables.java as shown in Code-2.13 below.  The modification is to create a couple of static variables and a couple of instance variables.
public class Variables {

// Static variables
static int staticintA = 10;
static String staticStringB =”I am static string”;

// Instance variables
int instanceintA = 20;
String instanceStringB = “I am instance string”;

}

Code-2.13: Variables.java

3. Modify StaticVariablesExamples.java to access static and instance variables of Variables class as shown in Code-2.14 below.

public class StaticVariablesExample {

public static void main(String[] args) {

// Access static variables of Variables class.
// Note that you don’t have to create an object instance
// of Variables class.
System.out.println(“Variables.staticintA = ” + Variables.staticintA);
System.out.println(“Variables.staticStringB = ” + Variables.staticStringB);
Variables.staticStringB = “Life is good!”;
System.out.println(“Variables.staticStringB = ” + Variables.staticStringB);

// Access instance variables of Variables class.
// Note that you have to create an object instance
// of Variables class before you access them.
Variables objectInstance1 = new Variables();
Variables objectInstance2 = new Variables();
objectInstance1.instanceintA = 1;
System.out.println(“objectInstance1.instanceintA = ” + objectInstance1.instanceintA);
objectInstance2.instanceintA = 3;
System.out.println(“objectInstance2.instanceintA = ” + objectInstance2.instanceintA);

// The static variable can be accessed from an object instance.
System.out.println(“objectInstance1.staticintA = ” + objectInstance1.staticintA);
objectInstance1.staticintA = 220;
System.out.println(“objectInstance1.staticintA = ” + objectInstance1.staticintA);
System.out.println(“Variables.staticintA = ” + Variables.staticintA);

// The static variable can be accessed from multiple object instances.
objectInstance2.staticintA = 550;
System.out.println(“objectInstance1.staticintA = ” + objectInstance1.staticintA);
System.out.println(“objectInstance2.staticintA = ” + objectInstance2.staticintA);
System.out.println(“Variables.staticintA = ” + Variables.staticintA);
}

}

Code-2.14: StaticVariablesExample.java

4. Build and run the program

  • Right click MyStaticVariablesExampleProject and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-2.15 below)
Variables.staticintA = 10
Variables.staticStringB = I am static string
Variables.staticStringB = Life is good!
objectInstance1.instanceintA = 1
objectInstance2.instanceintA = 3
objectInstance1.staticintA = 10
objectInstance1.staticintA = 220
Variables.staticintA = 220
objectInstance1.staticintA = 550
objectInstance2.staticintA = 550
Variables.staticintA = 550

Figure-2.15: Result

5. Observe compile error when you try to access instance variable as if it is a static variable.

  • Add the code fragment of Code-2.16 below to the StaticVariablesExample.java.
  • Observe the compile error.  (Figure-2.17 below)
  • Remove the code fragment you just added to remove the compile errors.
Variables.instanceintA = 3;

Code-2.16: Compile error


Figure-2.17: Compile error

Solution: The solutions to this exercise are provided as ready-to-open-and-run NetBeans projects as part of hands-on lab zip file. You can find them as <LAB_UNZIPPED_DIRECTORY>/javacreateclass/samples/MyStaticVariablesExampleProject and <LAB_UNZIPPED_DIRECTORY>/javacreateclass/samples/MyStaticMethodsExampleProject.  You can just open and run them.

6. (For your own exercise)  Modify StaticVariablesExample.java to display the addition of staticintA static variable and instanceintA instance variable.

(2.2) Build and run an application that uses static methods and non-static methods

0. Start the NetBeans IDE if you have not done so.
1. Create a NetBeans project

  • Select File from top-level menu and select New Project.
  • Observe that the New Project dialog box appears.
  • Select General under Categories section and Java Application under Projects section.
  • Click Next.
  • Under Name and Location pane, for the Project Name field, enter MyStaticMethodsExampleProject.
  • For the Create Main Class field, enter StaticMethodsExample.
  • Click Finish.
  • Observe that the MyStaticMethodsExampleProject project node is created under Projects pane of the NetBeans IDE and IDE generated StaticMethodsExample.java is displayed in the editor window of the IDE.

2. Write Methods.java.

  • Right click MyStaticMethodsExampleProject and select New->Java Class.
  • Observe that the Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter Methods.
  • Click Finish.
  • Observe that the IDE generated Methods.java is displayed in the editor window.
  • Modify the IDE generated Methods.java as shown in Code-2.21 below.  The modification is to create a couple of static and non-static methods.
public class Methods {

// Static variable
static int a = 0;

// Static method
static void staticMethod(int i) {
System.out.println(“staticMethod(“+ i +”) entered”);
}

// Anonymous static method.  The things inside the anonymous
// static method get executed when the class is loaded.
static {    //static block
System.out.println(“Anonymous static method entered, a = ” + a);
a += 1;  // same thing as a = a + 1
System.out.println(“Anonymous static method exiting, a = ” + a);
}

// Non-static method
void myNonStaticMethods(int i){
System.out.println(“myNonStaticMethod(“+ i +”) entered”);
}
}

Code-2.21: Methods.java

3. Modify StaticMethodsExamples.java to invoke static and non-static methods as shown in Code-2.22 below.

public class StaticMethodsExample {

public static void main(String[] args) {

// Access a static variable of Demo class.  Note that you don’t have to
// create an object instance of Demo class.
System.out.println(“Methods.a = ” + Methods.a);

// Invoke a static method of Methods class. Note that you don’t have to
// create an object instance of Methods class.
Methods.staticMethod(5);

// The static variable can be accessed from an object instance.
Methods d = new Methods();
System.out.println(“d.a = ” + d.a);

// The static method can be invoked from an object instance.
d.staticMethod(0);

// The same static variable can be accessed from multiple instances.
Methods e = new Methods();
System.out.println(“e.a = ” + e.a);
d.a += 3;
System.out.println(“Methods.a = ” + Methods.a);
System.out.println(“d.a = ” + d.a);
System.out.println(“e.a = ” + e.a);

// Compile error
// Methods.myNonStaticMethod(3);
}

}

Code-2.22: StaticMethodsExamples.java

4. Build and run the program

  • Right click MyStaticMethodsExampleProject and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-2.23 below)
Anonymous static method entered, a = 0
Anonymous static method exiting, a = 1
Methods.a = 1
staticMethod(5) entered
d.a = 1
staticMethod(0) entered
e.a = 1
Methods.a = 4
d.a = 4
e.a = 4

Figure-2.23: Result

5. Observe compile error when you try to invoke non-static method as if it is a static method.

  • Add the code fragment of Code-2.24 below to the StaticMethodsExample.java.
 Methods.myNonStaticMethod(3);

Code-2.24: Compile error expected

  • Observe the compile error.  (Figure-2.25 below)
  • Remove the code fragment you just added to remove the compile errors.


Figure-2.25: Compile error

Summary

In this exercise,  you have built and run Java applications that use static variables and static methods.

Exercise 3: Overloading

In this exercise, you are going to exercise the concept of overloading.  Please note that overloading and overriding are two different concepts.

(3.1) Use two overloaded methods to the StudentRecord class

1. Add two overloaded myprint() methods to the StudentRecored.java as shown in Code-3.11 below.  The code fragments that need to be added are highlighted in bold and blue-colored font.

public class StudentRecord {

// Declare instance variables.
private String name;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;

// Declare static variables.
private static int studentCount = 0;

/**
* Returns the name of the student
*/
public String getName(){
return name;
}

/**
* Changes the name of the student
*/
public void setName(String temp ){
name =temp;
}

/**
* Computes the average of the english,math and science
* grades
*/
public double getAverage(){
double result =0;
result =(getMathGrade()+getEnglishGrade()+getScienceGrade() )/3;
return result;
}

/**
* Returns the number of instances of StudentRecords
*/
public static int getStudentCount(){
return studentCount;
}

/**
* Increases the number of instances of StudentRecords
*/
public static void increaseStudentCount(){
studentCount++;
}

public double getMathGrade() {
return mathGrade;
}

public void setMathGrade(double mathGrade) {
this.mathGrade = mathGrade;
}

public double getEnglishGrade() {
return englishGrade;
}

public void setEnglishGrade(double englishGrade) {
this.englishGrade = englishGrade;
}

public double getScienceGrade() {
return scienceGrade;
}

public void setScienceGrade(double scienceGrade) {
this.scienceGrade = scienceGrade;
}

// Overloaded myprint(..) methods
public void myprint(){
System.out.println(“First overloaded method: Nothing is passed on”);
}

public void myprint(String name ){
System.out.println(“Second overloaded method: Name:”+name);
}

public void myprint(String name, double averageGrade){
System.out.print(“Third overloaded method: Name:”+name+” “);
System.out.println(“Average Grade:”+averageGrade);
}

}

Code-3.11: StaticAndInstanceMethods.java

3. Modify StudentRecoredExample.java as shown in Code-3.12 below.  The code fragments that need to be added are highlighted in bold and blue-colored font.

public class StaticVariblesMethods {

public static void main(String[] args) {

// Create an object instance of StudentRecord class.
StudentRecord annaRecord =new StudentRecord();

// Increament the studentCount by invoking a static method.
StudentRecord.increaseStudentCount();

// Create another object instance of StudentRecord class.
StudentRecord beahRecord =new StudentRecord();

// Increament the studentCount by invoking a static method.
StudentRecord.increaseStudentCount();

// Create the 3rd object instance of StudentRecord class.
StudentRecord crisRecord =new StudentRecord();

// Increament the studentCount by invoking a static method.
StudentRecord.increaseStudentCount();

// Set the names of the students.
annaRecord.setName(“Anna”);
beahRecord.setName(“Beah”);
crisRecord.setName(“Cris”);

// Print anna’s name.
System.out.println(“Name = ” + annaRecord.getName());

// Print number of students.
System.out.println(“Student Count = “+StudentRecord.getStudentCount());

// Set Anna’s grades
annaRecord.setName(“Anna”);
annaRecord.setEnglishGrade(95.5);
annaRecord.setScienceGrade(100);

// Invoke overloaded methods
annaRecord.myprint();
annaRecord.myprint(annaRecord.getName());
annaRecord.myprint(annaRecord.getName(), annaRecord.getAverage());

}

}

Code-3.12: Call overloaded methods

4. Build and run the program

  • Right click MyStudentRecordExampleProject and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-3.13 below)
Name = Anna
Student Count = 3
First overloaded method: Nothing is passed on
Second overloaded method: Name:Anna
Third overloaded method: Name:Anna Average Grade:65.16666666666667

Figure-3.13: Result

5. (For your own exercise) Do make changes as following and build and run the applicaiton.

  • Modify StudentRecord.java as following
    • Add another overloaded myprint() method which takes the following three parameters
      • name, grade average, student count
  • Modify StudentRecordExmaple.java as following
    • Invoke the newly added myprint() method

Summary

In this exercise,  you have exercises how to use overloaded methods.

 

 

Exercise 4: Constructors

In this exercise, you will exercise the concept of constructors.

  1. Exercise multiple constructors
  2. Chaining of constructors via this() method

(4.1)  Exercise multiple construcors

1. Create a NetBeans project

  • Select File from top-level menu and select New Project.
  • Observe that the New Project dialog box appears.
  • Select General under Categories section and Java Application under Projects section.
  • Click Next.
  • Under Name and Location pane, for the Project Name field, enter MyConstructorExampleProject.
  • For the Create Main Class field, enter ConstructorExample.
  • Click Finish.
  • Observe that the MyConstructorExampleProject project node is created under Projects pane of the NetBeans IDE and IDE generated ConstructorExample.java is displayed in the editor window of the IDE.
2. Write StudentRecord.java.
  • Right click MyConstructorExampleProject and select New->Java Class.
  • Observe that the Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter StudentRecord.
  • Click Finish.
  • Observe that the IDE generated StudentRecord.java is displayed in the editor window.
  • Modify the IDE generated StudentRecord.java as shown in Code-4.11 below.  Note that change is to add multiple construcors to the StudentRecord class.
public class StudentRecord {

// Declare instance variables.
private String name;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;

// Declare static variables.
private static int studentCount = 0;

// Default constructor
public StudentRecord() {
}

// Constructor that gets single parameter
public StudentRecord(String name){
this.name = name;
}

// Constructor that gets two parameters
public StudentRecord(String name, double mGrade){
this.name = name;
mathGrade = mGrade;
}

// Constructor that gets three parameters
public StudentRecord(String name, double mGrade, double eGrade){
this.name = name;
mathGrade = mGrade;
englishGrade = eGrade;
}

// Constructor that gets four parameters
public StudentRecord(String name, double mGrade, double eGrade,
double sGrade){
this.name = name;
mathGrade = mGrade;
englishGrade = eGrade;
scienceGrade = sGrade;
}

/**
* Returns the name of the student
*/
public String getName(){
return name;
}

/**
* Changes the name of the student
*/
public void setName(String temp ){
name =temp;
}

/**
* Computes the average of the english,math and science
* grades
*/
public double getAverage(){
double result =0;
result =(getMathGrade()+getEnglishGrade()+getScienceGrade() )/3;
return result;
}

/**
* Returns the number of instances of StudentRecords
*/
public static int getStudentCount(){
return studentCount;
}

/**
* Increases the number of instances of StudentRecords.
* This is a static method.
*/
public static void increaseStudentCount(){
studentCount++;
}

// Instance methods
public double getMathGrade() {
return mathGrade;
}

public void setMathGrade(double mathGrade) {
this.mathGrade = mathGrade;
}

public double getEnglishGrade() {
return englishGrade;
}

public void setEnglishGrade(double englishGrade) {
this.englishGrade = englishGrade;
}

public double getScienceGrade() {
return scienceGrade;
}

public void setScienceGrade(double scienceGrade) {
this.scienceGrade = scienceGrade;
}
}

Code-4.11: StudentRecord.java that has multiple constructors

3. Modify the IDE generated ConstructorExample.java as shown in Code-4.12.

  • Study the code while paying special attention to the bold-fonted comments.
  • Observe that ConstructorExample class uses StudentRecord class.
public class ConstructorExample {

public static void main(String[] args) {

// Create an object instance of StudentRecord class.
StudentRecord annaRecord = new StudentRecord(“Anna”);

// Increament the studentCount by invoking a static method.
StudentRecord.increaseStudentCount();

// Create another object instance of StudentRecord class.
StudentRecord beahRecord =new StudentRecord(“Beah”, 45);

// Increament the studentCount by invoking a static method.
StudentRecord.increaseStudentCount();

// Create the 3rd object instance of StudentRecord class.
StudentRecord crisRecord =new StudentRecord(“Cris”, 23.3, 67.45, 56);

// Increament the studentCount by invoking a static method.
StudentRecord.increaseStudentCount();

// Print Cris’ name and average
System.out.println(“Name = ” + crisRecord.getName() + ” Average = ” + crisRecord.getAverage());

// Print number of students.
System.out.println(“Student Count = “+StudentRecord.getStudentCount());
}

}

Code-4.12: ConstructorExample.java

4. Build and run the program

  • Right click MyConstructorExampleProject and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-4.13 below)
Name = Cris Average = 48.916666666666664
Student Count = 3

Figure-4.13: Result

5. (For your own exercise) Modify StudentRecord.java and ConstructorExample.java as following. Build and run the project.

  • Create another Constructor in the StudentRecord.java in which average is also passed as a parameter.
  • Modify the ConstructorExample.java so that StudentRecord annaRecord object is created with the newly added Constructor.

(4.2) Chaining of contructors via this() method

1. Modify StuentRecord.java as shown in Code-4.20 below.

public class StudentRecord {

// Declare instance variables.
private String name;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;

// Declare static variables.
private static int studentCount = 0;

// Default constructor
public StudentRecord() {
}

// Constructor that gets single parameter
public StudentRecord(String name){
this.name = name;
}

// Constructor that gets two parameters
public StudentRecord(String name, double mGrade){
this(name);
mathGrade = mGrade;
}

// Constructor that gets three parameters
public StudentRecord(String name, double mGrade, double eGrade){
this(name, mGrade);
englishGrade = eGrade;
}

// Constructor that gets four parameters
public StudentRecord(String name, double mGrade, double eGrade,
double sGrade){
this(name, mGrade, eGrade);
scienceGrade = sGrade;
}

/**
* Returns the name of the student
*/
public String getName(){
return name;
}

/**
* Changes the name of the student
*/
public void setName(String temp ){
name =temp;
}

/**
* Computes the average of the english,math and science
* grades
*/
public double getAverage(){
double result =0;
result =(getMathGrade()+getEnglishGrade()+getScienceGrade() )/3;
return result;
}

/**
* Returns the number of instances of StudentRecords
*/
public static int getStudentCount(){
return studentCount;
}

/**
* Increases the number of instances of StudentRecords.
* This is a static method.
*/
public static void increaseStudentCount(){
studentCount++;
}

// Instance methods
public double getMathGrade() {
return mathGrade;
}

public void setMathGrade(double mathGrade) {
this.mathGrade = mathGrade;
}

public double getEnglishGrade() {
return englishGrade;
}

public void setEnglishGrade(double englishGrade) {
this.englishGrade = englishGrade;
}

public double getScienceGrade() {
return scienceGrade;
}

public void setScienceGrade(double scienceGrade) {
this.scienceGrade = scienceGrade;
}
}

Code-4.20: Modified StudentRecord.java

2. Build and run the program

  • Right click MyConstructorExampleProject and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-4.21 below)
Name = Cris Average = 48.916666666666664
Student Count = 3

Figure-4.21: Result

3. (For your own exercise) Modify StudentRecord.java and ConstructorExample.java as following:

  • Create another Constructor in the StudentRecord.java in which average is also passed as a parameter.
  • Modify the ConstructorExample.java so that StudentRecord annaRecord object is created with the newly added Constructor.
 

Summary

In this exercise,  you learned you can have overloaded methods in a class. You also learned how to invoke a particular overloaded method by passing different set of parameters.

Exercise 5: “this” reference

In this exercise, you will exercise the concept of “this” reference.

  1. “this” reference in method call
  2. “this” reference as a parameter

(5.1)  “this” reference in method call

1. Create a NetBeans project

  • Select File from top-level menu and select New Project.
  • Observe that the New Project dialog box appears.
  • Select General under Categories section and Java Application under Projects section.
  • Click Next.
  • Under Name and Location pane, for the Project Name field, enter MyThisReferenceExampleProject.
  • For the Create Main Class field, enter ThisReferenceExample.
  • Click Finish.
  • Observe that the MyThisReferenceExampleProject project node is created under Projects pane of the NetBeans IDE and IDE generated ThisReferenceExample.java is displayed in the editor window of the IDE.
2. Write DummyClass.java.
  • Right click MyThisReferenceExampleProject and select New->Java Class.
  • Observe that the Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter DummyClass.
  • Click Finish.
  • Observe that the IDE generated DummyClass.java is displayed in the editor window.
  • Modify the IDE generated DummyClass.java as shown in Code-5.10 below.
public class DummyClass {

void mymethod1(){

// Note that mymethod2() and this.mymethod2() are the same thing.
String s1 = mymethod2(“Sang Shin”);
String s2 = this.mymethod2(“Sang Shin”);

System.out.println(“s1 = ” + s1 + ” s2 = ” + s2);
}

String mymethod2(String name){
return “Hello ” + name;
}

}

Code-5.10: DummyClass.java

3. Modify ThisReferenceExample.java as shown Code-5.11 below.

public class ThisReferenceExample {

public static void main(String[] args) {
DummyClass d1 = new DummyClass();
d1.mymethod1();
}
}

Code-5.11: ThisReferenceExample.java

4. Build and run the program

  • Right click  MyThisReferenceExampleProject and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-5.12 below)
s1 = Hello Sang Shin s2 = Hello Sang Shin

Figure-5.12: Result

5. Modify DummyClass.java as shown in Code-5.13 below.

public class DummyClass {

void mymethod1(){

// Note that mymethod2() and this.mymethod2() are the same thing.
String s1 = mymethod2(“Sang Shin”);
String s2 = this.mymethod2(“Sang Shin”);

System.out.println(“s1 = ” + s1 + ” s2 = ” + s2);
}

String mymethod2(String name){
return “Hello ” + name;
}

// Compile error – you cannot invoke instance method
// from a static method.
static void mymethod3(){
String s1 = mymethod2(“Sang Shin”);
String s2 = this.mymethod2(“Sang Shin”);
System.out.println(“s1 = ” + s1 + ” s2 = ” + s2);
}

}

Code-5.13: Compile error when a static method invokes instance method

6. Observe the compile error. (Figure-5.14 below)


Figure-5.14: Compile error

(5.2)  “this” reference as a parameter

1. Modify DummyClass.java as shown in Code-5.15 below.  The code fragments that need to be added are highlighted in bold and blue-colored font.

public class DummyClass {

void mymethod1(){

// Note that mymethod2() and this.mymethod2() are the same thing.
String s1 = mymethod2(“Sang Shin”);
String s2 = this.mymethod2(“Sang Shin”);

System.out.println(“s1 = ” + s1 + ” s2 = ” + s2);

// Pass the current object instance as a parameter
String s3 = this.mymethod3(this);
System.out.println(“s3 = ” + s3);
}

String mymethod2(String name){
return “Hello ” + name;
}

String mymethod3(Object o1){
return o1.getClass().getName();
}

}

Code-5.15: Modified DummyClass.java

2. Build and run the program

  • Right click  MyThisReferenceExampleProject and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-5.17 below)
s1 = Hello Sang Shin s2 = Hello Sang Shin
s3 = DummyClass

Figure-5.17: Result

3. Modify DummyClass.java as shown in Code-5.18 below.  The code fragments that need to be added are highlighted in bold and blue-colored font.

public class DummyClass {

String hello =”Hello”;
String bye = “Bye”;

void mymethod1(){

// Note that mymethod2() and this.mymethod2() are the same thing.
String s1 = mymethod2(“Sang Shin”);
String s2 = this.mymethod2(“Sang Shin”);

System.out.println(“s1 = ” + s1 + ” s2 = ” + s2);

// Pass the current object instance as a parameter
String s3 = this.mymethod3(this, this.hello);
System.out.println(“s3 = ” + s3);

s3 = this.mymethod3(this, this.bye);
System.out.println(“s3 = ” + s3);
}

String mymethod2(String name){
return “Hello ” + name;
}

String mymethod3(Object o1, String s){
return s + ” ” + o1.getClass().getName();
}

}

Code-5.18: Modifed DummyClass.java

4. Build and run the program

  • Right click  MyThisReferenceExampleProject and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-5.19 below)
s1 = Hello Sang Shin s2 = Hello Sang Shin
s3 = Hello DummyClass
s3 = Bye DummyClass

Figure-5.19: Result

Summary

In this exercise,  you learned how to use “this” reference.

Exercise 6: Access modifiers – private, protected, and public

In this exercise, you will exercise access modifiers for the variables and methods.

(6.1) Exercise access modifiers within a same package

1. Create a NetBeans project

  • Select File from top-level menu and select New Project.
  • Observe that the New Project dialog box appears.
  • Select General under Categories section and Java Application under Projects section.
  • Click Next.
  • Under Name and Location pane, for the Project Name field, enter MyAccessModifierExampleProject. (Figure-6.10 below)
  • For the Create Main Class field, leave it to the IDE generated value myaccessmodifierexampleProject.Main.  This is going to generate Main class under myaccessmodifieexampleproject package.
  • Click Finish.


Figure-6.10: Create a new project

2. Write DummyClass.java under myaccessmodifieexampleproject package.

  • Right click MyAccessModifierExampleProject and select New->Java Class.
  • Observe that the Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter DummyClass.  (Figure-6.11 below)
  • For the Package field, type in or choose myaccessmodifierexampleproject from the drop-down menu.
  • Click Finish.


Figure-6.11: Create DummyClass

  • Observe that the IDE generated DummyClass.java is displayed in the editor window.
  • Modify the IDE generated DummyClass.java as shown in Code-6.12 below.   Study the code by paying special attention to the bold-fonted comments.
package myaccessmodifierexampleproject;

public class DummyClass {

// Private field. Can be accessed only within the
// same class.
private String s1 = “private string”;

// Protected field. Can be accessed only within
// the same package.
protected String s2 = “protected string”;

// Public field. Can be accessed from anybody.
public String s3 = “public string”;

// Default is protected
String s4 = “string without access modifier”;

// Private method. Can be accessed only within the
// same class.
private void method1(){
}

// Protected method. Can be accessed only within
// the same package.
protected void method2(){
}

// Public method. Can be accessed from anybody.
public void method3(){
}

// Default is protected.
void method4(){
}
}

Code-6.12: DummyClass.java

3. Modify Main.java as shown in Code-6.13 below.

package myaccessmodifierexampleproject;

public class Main {

/** Creates a new instance of Main */
public Main() {
}

public static void main(String[] args) {
DummyClass t = new DummyClass();

// Compiler error expected
System.out.println(“s1 = ” + t.s1);  // accessing private variable of DummayClass class

// No compile error expected
System.out.println(“s2 = ” + t.s2);  // accessing protected variable
System.out.println(“s3 = ” + t.s3);  // accessing public variable
System.out.println(“s4 = ” + t.s4);  // accessing default access modifier variable

// Compiler error expected
t.method1();  // calling private method of DummyClass class

// No compile error expected
t.method2();  // calling protected method
t.method3();  // calling public method
t.method4();  // calling default access modifier method
}

}

Code-6.13: Modified Main.java

  • Observe the compile errors. (Figure-6.14 below)


Figure-6.14: Observe the compile errors.

return to top of the exercise

(6.2) Exercise access modifiers from a different package

1. Create a new package.
  • Right click Source Packages under MyAccessModifierExampleProject project node and select New->Java Package. (Figure-6.20 below)


Figure-6.20: Create a new Java package

  • Observe that the New Java Package dialog box appears.
  • For the Package Name field, enter mynewpackage.
  • Click Finish.


Figure-6.21: Give a package name

  • Observe that the mynewpackage package node appears.

2. Create a class under a new package.  You are going to access fields and methods of DummyClass from this new class.

  • Right click mynewpackage package node, and select New->Java Class. (Figure-6.22 below)


Figure-6.22: Create a new Java class under mynewpackage package

  • Observe that the New Java Class dialog box appears.
  • For Class Name field, type in DummyClass2.
  • Click Finish.


Figure-6.23: Create DummyClass2

  • Observe that IDE generated DummyClass2.java appears in the source editor window of NetBeans IDE.
  • Modify DummyClass2.java as shown in Code-6.24 below.
package mynewpackage;

//Import DummyClass
import myaccessmodifierexampleproject.DummyClass;

public class DummyClass2 {

public DummyClass2() {

DummyClass t = new DummyClass();

// Compiler error expected
System.out.println(“s1 = ” + t.s1);  // accessing private variable of DummayClass class
System.out.println(“s2 = ” + t.s2);  // accessing protected variable
System.out.println(“s4 = ” + t.s4);  // accessing default access modifier variable
t.method1();  // calling private method of DummyClass class
t.method2();  // calling protected method
t.method4();  // calling default access modifier method

// No compile error expected
System.out.println(“s3 = ” + t.s3);  // accessing public variable
t.method3();  // calling public method
}

}

Code-6.24: DummyClass2.java

3. Observe the compile errors. (Figure-6.25 below)


Figure-6.25: Compile errors

Summary

In this exercise,  you learned how to use access modifiers to constrain the access privilege between classes.

Homework exercise (for people who are taking Sang Shin’s “Java Programming online course”)

 

1. The homework is to either modify MyStudentRecordExampleProject NetBeans project you’ve done in Exercise 1 above or create a new project as following.  (You might want to create a new project by copying the MyStudentRecordExampleProject project.  You can name the homework project in any way you want but here I am going to call it MyOwnProject.)
  • Create a Student class as following:
    • The Student class has StudentRecord class as an instance variable.  Name it as studentRecord.
      • You can use the StudentRecord class from the MyStudentRecordExampleProject above or you can create a new one – the only requirement is that it has to have at least one instance variable of its own.
    • The Student class has studentId instance variable whose type is Integer type.
    • Move the studentCount static variable from the StudentRecord class to Student class.
  • Rewrite main.java as following
    • Create 3 instances of Student class and initialize them accordingly – use whatever initialization values that  are appropriate.
    • Display the information of each student including the student id, name.
    • Display the studentCount.
2. Send the following files to javaprogramminghomework@sun.com with Subject as JavaIntro-javacreateclass.
  • Zip file of the the MyOwnProject NetBeans project.  (Someone else should be able to open and run it as a NetBeans project.)  You can use your favorite zip utility or you can use “jar” utility that comes with JDK as following.
    • cd <parent directory that contains MyOwnProject directory> (assuming you named your project as MyOwnProject)
    • jar cvf MyOwnProject.zip MyOwnProject (MyOwnProject should contain nbproject directory)
  • Captured output screen  – name it as JavaIntro-javacreateclass.gif orJavaIntro-javacreateclass.jpg (or JavaIntro-javacreateclass.<whatver graphics format>)
    • Any screen capture that shows that your program is working is good enough.  No cosmetic polishment is required.
  • If you decide to use different IDE other than NetBeans, the zip file should contain all the files that are needed for rebuilding the project.

 

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.