Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Lecture 2 - Java Programming-Classes and Objects.docx

Uploaded by

hassan992018
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture 2 - Java Programming-Classes and Objects.docx

Uploaded by

hassan992018
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Java Programming 2nd Lecture

Introduction to Classes, Objects, Methods and Strings

Topics

 Introduction
 Defining Classes for Objects
 Example “GradeBook”
 Class “GradeBookTest”
 Object Creation
 Instance Variables, set Methods and get Methods
 Initializing Objects with Constructors
1- Introduction
Object-oriented programming enables programmer to develop large-scale software and GUIs
effectively. Classical programming with selections, loops, methods, and arrays can solve many
programming problems.
However, these Java features are not sufficient for developing graphical user interfaces and
large-scale software systems.

2- Defining Classes for Objects


Object-oriented programming (OOP) involves programming using objects. An object represents
an entity in the real world that can be distinctly identified. For example, a student, a desk, a
circle, a button, and even a loan can all be viewed as objects. An object has a unique identity,
state, and behavior.

3- Example “GradeBook”

In this section a new class is created then it is used to create an object.


Initially a class “GradeBook” is declared as shown in listing 1, while the “GradeBookTest” class is
declared in listing 2.

 The GradeBook class will be used to display a message on the screen which is
welcoming the instructor to the grade book application.

 Class GradeBookTest (declared in the file GradeBookTest.java) is an application class


in which the main method will create and use an object of class “GradeBook”.

 Each class declaration that begins with keyword public must be stored in a file having
the same name as the class and ending with the .java file-name extension.

 Thus, classes “GradeBook” and “GradeBookTest” must be declared in separate files,


because each class is declared public.

The GradeBook class declaration contains a displayMessage method (lines 7– 10) that displays
a message on the screen. It is needed to make an object of this class and call its method to
execute line 9 and display the message.
The class declaration begins in line 4. The keyword public is an access modifier. Every class
declaration contains keyword class followed immediately by the class’s name.
Listing 1
1 // GradeBook.java
2 // Class declaration with one method.
3
4 public class GradeBook
5 {
6 // display a welcome message to the GradeBook user
7 public void displayMessage()
8 {
9 System.out.println( "Welcome to the Grade Book!" );
10 } // end method displayMessage
11 } // end class GradeBook

In listing 1 code, the method declaration begins with keyword public to indicate that the method
is “available to the public” i.e. it can be called from methods of other classes.
Next is the method’s return type, which specifies the type of data the method returns to its
caller after performing its task. The return type void indicates that this method will perform a
task but will not return (i.e., give back) any information to its calling method.

4-Class “GradeBookTest”

Now, the GradeBook class is used within an application, as mentioned earlier the method main
begins the execution of every application.

 A class that contains method main begins the execution of a Java application.

 Class “GradeBook” is not an application because it does not contain main. Therefore, in
case trying to execute “GradeBook” by typing java GradeBook in the command
window, an error will occur.

 This problem is fixed by either declaring a separate class that contains a main method or
place a main method in class GradeBook. To be prepared for developing larger
programs in future projects, the first approach is followed. Therefore, a
“GradeBookTest” is used for testing the “GradeBook” class, the class used for this
purpose is known as the driver class.

 The GradeBookTest class is known as a driver class.


The GradeBookTest class declaration in Listing 2 contains the main method that will control
the application’s execution.

Listing 2
1 public class GradeBookTest
2{
3 // main method begins program execution
4 public static void main( String[ ] args )
5 {
6 // create a GradeBook object and assign it to myGradeBook
7 GradeBook myGradeBook = new GradeBook( );
8
9 // call myGradeBook's displayMessage method
10 myGradeBook.displayMessage( );
11 } // end main
12 } // end class GradeBookTest

In this application, it is required to call class GradeBook’s displayMessage method to display


the welcome message in the command window. Typically, it is not possible to call a method
that belongs to another class until the creation of an object of that class, as shown in line 7. So,
the variable “myGradeBook” is declared. The variable’s type is GradeBook, which is the class
was declared in Listing1. Each newly created class becomes a new type that can be used to
declare variables and create objects.

5- Object Creation
 In line 7 of Listing 2, variable myGradeBook is initialized with the result of the class
instance creation expression “new GradeBook( )”.
 Keyword new creates a new object of the class specified to the right of the keyword
(i.e., GradeBook).
 The parentheses to the right of GradeBook are required. As it will be seen later, those
parentheses in combination with a class name represent a call to a constructor, which is
similar to a method but is used only at the time an object is created to initialize the
object’s data.
 It can be seen that data can be placed in the parentheses to specify initial values for the
object’s data. For now, we simply leave the parentheses empty.
6- Declaring a Method with a Parameter “Argument to method”
Now the GradeBook class is declared with a displayMessage method that displays the course
name as part of the welcome message as shown in Listing 3.

Listing 3

1 public class GradeBook


2 {
3 // display a welcome message to the GradeBook user
4 public void displayMessage(String courseName )
5 {
6 System.out.printf( "Welcome to the grade book for\n%s!\n",
7 courseName );
6
7
8 } // end method displayMessage
9 } // end class GradeBook

Listing 4
1 import java.util.Scanner; // program uses Scanner
2
3 public class GradeBookTest
4{
5 // main method begins program execution
6 public static void main( String[ ] args )
7 {
8 // create Scanner object to obtain input from command window
9 Scanner input = new Scanner( System.in );
10
11 // create a GradeBook object and assign it to myGradeBook
12 GradeBook myGradeBook = new GradeBook( );
13
14 // prompt for and input course name
15 System.out.println( "Please enter the course name:" );
16 String nameOfCourse = input.nextLine( ); // read a line of text
17 System.out.println( ); // outputs a blank line
18
19 // call myGradeBook's displayMessage method
20 // and pass nameOfCourse as an argument
21 myGradeBook.displayMessage( nameOfCourse );
22 } // end main
23 } // end class GradeBookTest
Note1: There’s a special relationship between classes that are compiled in the same directory on
disk, like classes “GradeBook” and “GradeBookTest”. By default, such classes are considered
to be in the same package known as the default package. Classes in the same package are
implicitly imported into the source-code files of other classes in the same package. Thus, an
import declaration is not required when one class in a package uses another in the same package
such as when class “GradeBookTest” uses class “GradeBook”.

Note2: The import declaration in line 1 is not required if we always refer to class Scanner as
java.util.Scanner, which includes the full package name and class name. This is known as the
class’s fully qualified class name. For example, line 9 could be written as:

java.util.Scanner input = new java.util.Scanner( System.in );

7- Instance Variables, set Methods and get Methods


an object has attributes that are carried with it as it’s used in a program. Such attributes exist
before a method is called on an object, while the method is executing and after the method
completes execution.
A class normally consists of one or more methods that manipulate the attributes that belong to a
particular object of the class. Attributes are represented as variables in a class declaration. Such
variables are called fields and are declared inside a class declaration but outside the bodies of
the class’s method declarations. When each object of a class maintains its own copy of an
attribute, the field that represents the attribute is also known as an instance variable.

Listing 5
1 public class GradeBook
2{
3 private String courseName; // course name for this GradeBook
4
5 public void setCourseName( String name) //method to setthe course name
6 {
7 courseName = name; // store the course name
8 } // end method setCourseName
9 // method to retrieve the course name
10 public String getCourseName( )
11 {
12 return courseName;
13 } // end method getCourseName
14 // display a welcome message to the GradeBook user
15 public void displayMessage
16 {
17 // calls getCourseName to get the name of the course this GradeBook represents
18
19 System.out.printf( "Welcome to the grade book for\n%s!\n",
20 getCourseName( ) );
21 } // end method displayMessage
22 } // end class GradeBook

Listing 6
1 import java.util.Scanner; // program uses Scanner
2
3 public class GradeBookTest
4 {
5 // main method begins program execution
6 public static void main( String[ ] args )
7 {
8 // create Scanner to obtain input from command window
9 Scanner input = new Scanner( System.in );
10
11 // create a GradeBook object and assign it to myGradeBook
12 GradeBook myGradeBook = new GradeBook( );
16 // display initial value of courseName
17 System.out.printf( "Initial course name is: %s\n\n",
18 myGradeBook.getCourseName( ) );
19
20 // prompt for and read course name
21 System.out.println( "Please enter the course name:" );
22 String theName = input.nextLine( ); // read a line of text
23 myGradeBook.setCourseName( theName ); // set the course name
24 System.out.println( ); // outputs a blank line
25
26 // display welcome message after specifying course name
27 myGradeBook.displayMessage( );
28 } // end main
29 } // end class GradeBookTest
8-Initializing Objects with Constructors
As mentioned in the previous section, when an object of class GradeBook is created, its
instance variable “courseName” is initialized to null by default. What if it is required to provide
a course name when a GradeBook object is created?

 Each class declared can provide a special method called a constructor that can be used
to initialize an object of a class when the object is created.

 Java requires a constructor call for every object that’s created. Keyword “new” requests
memory from the system to store an object, then calls the corresponding class’s
constructor to initialize the object. The call is indicated by the parentheses after the class
name. A constructor must have the same name as the class.

 The empty parentheses after “new GradeBook” indicate a call to the class’s constructor
without arguments. By default, the compiler provides a default constructor with no
parameters in any class that does not explicitly include a constructor. When a class has
only the default constructor, its instance variables are initialized to their default values.

When a class is declared, it is possible to provide a customized constructor to specify values for
objects of that class.
For example, it could be required to specify a course name for a GradeBook object when the
object is created, as follows:
GradeBook myGradeBook = new GradeBook( "CS101 Introduction to Java Programming" );

This can be illustrated in a complete program as shown in listing 7:

Listing 7
1 public class GradeBook
2{
3 private String courseName; // course name for this GradeBook
4 public GradeBook( String name ) // constructor name is class name
5 {
6 courseName = name; // initializes courseName
7 }
8 // method to set the course name
9 public void setCourseName( String name )
10 {
11 courseName = name; // store the course name
12 } // end method setCourseName
13 // method to retrieve the course name
14 public String getCourseName( )
15 {
16 return courseName;
17 } // end method getCourseName
18 // display a welcome message to the GradeBook user
19 public void displayMessage
20 {
21 // calls getCourseName to get the name of the course this GradeBook represents
22
23 System.out.printf( "Welcome to the grade book for\n%s!\n",
24 getCourseName( ) );
25 } // end method displayMessage
26 } // end class GradeBook

1 public class GradeBookTest


2 {
3 // main method begins program execution
4 public static void main( String[ ] args )
5 {
6 // create GradeBook object
7 GradeBook gradeBook1 = new GradeBook(
8 "CS101 Introduction to Java Programming" );
9 GradeBook gradeBook2 = new GradeBook(
10 "CS102 Data Structures in Java" );
11
12 System.out.printf( "gradeBook1 course name is: %s\n",
13 gradeBook1.getCourseName() );
14 System.out.printf( "gradeBook2 course name is: %s\n",
15 gradeBook2.getCourseName() );
16 } // end main
17 } // end class GradeBookTest

You might also like