Topic B – Starting Classes
Overview
This topic introduces some of the basic syntax and grammar surrounding Object-Oriented Programming in Java. The following keywords are introduced. (Note that additional keywords from previous topics may also be present.)
- new
- char
- int
- double
This topic will also introduce the following grammars, syntax and language constructs. (Note that additional concepts from previous topics may also be present.)
- Method declaration syntax (instance methods)
- Object instantiation
- Instance method call syntax (with and without arguments)
- Class Field declaration syntax (member variables)
- Assignment statement syntax
- Accessing public fields in objects (storing & retrieving values)
Note that this package introduces the distinction between static and non-static methods. Static methods, also known as “class methods”, are identified by the keyword static and must be qualified by the class name; for example, in the following method call Salutation is the name of the class and Greeting is a static method of that class.Salutation.Greeting()
Non-static methods, also known as “instance methods”, are identified by the absence of the static keyword and must be called by using an instance of the class (that is, an object). An example of calling an instance method would beapp.Greeting()
where the app is an instance of the Salutation class.
LOGs
At the end of this topic, you should be able to …
OOP Basics
- Define the term “object” as used in OOP
- Describe the syntax of static and non-static method declarations
- Compare and contrast the syntax for method declarations (implementations) vs. method calls (for both static and non-static methods)
- Define the term “field” as used in OOP and give an example
- Compare and contrast instance and class members, for both methods and fields
- Identify the “member access operator” and explain it’s purpose
- Create (instantiate) objects
- Distinguish between classes and objects in OOP
- Explain what is meant by the phrase “type extensibility” and how classes represent “complex” data types in OOP
General Programming Concepts and Terms
- List the three categories of simple information
- Define the term “intrinsic data type”
- Explain what an assignment statement is and how it works
- Compare and contrast the three categories of simple information with the complex types of information which classes represent
- Explain the advantages of using classes and objects instead of only using intrinsic data types
Code Samples
The following examples are used to illustrate this topic.
- Salutation - This adaptation of the classic “Hello World” program illustrates instance methods. This example includes and introduces the concept of a “driver” and the idea of creating (instantiating) an object based on a class.
- Person - This simple class illustrates and introduces the idea of fields (member variables) of a class. This example includes and introduces the idea of a driver. The driver also illustrates how a single class can be used to instantiate multiple, distinct objects.
- Account - This simple class also illustrates fields. This example includes a driver.
- Comments - This class continues the illustration of the kinds of comments allowed in the programming language. This class builds on the previous example by showing comments for fields as well as methods.
- Student - This class introduces a slightly more complex class by offering more fields. This example includes two drivers. By using two drivers, this illustrates that separate “programs” can share/use the same class definition.
- The first driver is a simple “test driver” to ensure that the class is “working”. This introduces the student to the idea that it is necessary to “test” or prove that the code we are creating is valid.
- The second driver illustrates how the a single class can act as the basis for creating many distinct objects.
- Employee + Company - These are other classes similar to the Person and Student classes. These classes, however, “share” a driver, illustrating the fact that any given “program” typically uses more than one class. In addition, this driver introduces the ToString() and Parse() methods of the DateTime class.
Salutation & Driver
This adaptation of the classic “Hello World” program illustrates instance methods. This example includes and introduces the concept of a “driver” and the idea of creating (instantiating) an object based on a class.
1 /*
2 * Purpose: To illustrate
3 * - Keywords: public, class, return
4 * - Grammar: method declaration, parameter declaration, single line co\
5 mments
6 * - Other:
7 * - string data type
8 * - method overloading
9 * - Instance members
10 */
11 namespace Topic.B.Examples
12 {
13 public class Salutation
14 {
15 public string Greeting()
16 {
17 return "Hello World!";
18 }
19
20 public string Greeting(string name)
21 {
22 return "Hello " + name;
23 }
24 }
25 }
1 /*
2 * Purpose: To illustrate
3 * - Keywords: public, class, static, void, new
4 * - Grammar: variable (object) declaration, object instantiation, meth\
5 od declaration, method call, multi-line comments
6 * - Other:
7 * - main - the entry level of every program
8 * - console output (println)
9 * - Instance vs. Class methods
10 * - instance method call
11 * - instance method call with argument
12 * - (optional) array declaration - string[]
13 */
14 namespace Topic.B.Examples
15 {
16
17 public class HelloWorld_Driver
18 {
19 public static void Main(string[] args)
20 {
21 Salutation app = new Salutation();
22
23 System.Console.WriteLine(app.Greeting());
24 System.Console.WriteLine(app.Greeting("Bob"));
25 }
26 }
27 }
Person
This simple class illustrates and introduces the idea of fields (member variables) of a class. This example includes and introduces the idea of a driver. The driver also illustrates how a single class can be used to instantiate multiple, distinct objects.
- Data Attributes of the Person class:
- FirstName : String
- LastName : String
- Age : Integer
1 namespace Topic.B.Examples
2 {
3 public class Person
4 {
5 /// <summary>This is the first name of the person</summary>
6 public string FirstName;
7 /// <summary>This is the last name of the person</summary>
8 public string LastName;
9 /// <summary>This is the person's age</summary>
10 public int Age;
11 }
12 }
1 namespace Topic.B.Examples
2 {
3 public class DemoPerson
4 {
5 public static void Main(string[] args)
6 {
7 Person someGuy;
8 someGuy = new Person();
9 someGuy.FirstName = "Harry";
10 someGuy.LastName = "Burns";
11 someGuy.Age = 25;
12
13 Person someGirl;
14 someGirl = new Person();
15 someGirl.FirstName = "Sally";
16 someGirl.LastName = "Albright";
17 someGirl.Age = 25;
18
19 string fullName;
20
21 fullName = someGuy.FirstName + " " + someGuy.LastName;
22 System.Console.WriteLine("Hi. My name is " + fullName);
23
24 fullName = someGirl.FirstName + " " + someGirl.LastName;
25 System.Console.WriteLine("Hi" + someGuy.FirstName +
26 ". My name is " + fullName);
27 }
28 }
29 }
Account
This simple class also illustrates fields. This example includes a driver.
* Data Attributes of the Account class:
* AccountNumber : Integer
* Balance : Real
* OverdraftLimit : Double
1 namespace Topic.B.Examples
2 {
3 public class Account
4 {
5 public int AccountNumber;
6 public double Balance;
7 public double OverdraftLimit;
8 }
9 }
1 namespace Topic.B.Examples
2 {
3 public class DemoAccountDriver
4 {
5 public static void Main(string[] args)
6 {
7 Account myAccount; // declares a reference variable to an Account ob\
8 ject
9 myAccount = new Account(); // creates the Account object.
10
11 myAccount.Balance = 500000.00;
12 myAccount.OverdraftLimit = 1000000.00;
13 myAccount.AccountNumber = 123456;
14 }
15 }
16 }
Comments
This class continues the illustration of the kinds of comments allowed in the programming language. This class builds on the previous example by showing comments for fields as well as methods.
1 /*
2 * File: Comments.cs
3 * Author: Dan Gilleland
4 * Date: 2010
5 * Purpose: To illustrate multi-line, single-line, and XML comments.
6 * This is a multi-line comment.
7 */
8 namespace Topic.B.Examples
9 {
10 /// <summary>
11 /// Comments illustrates multi-line, single-line, and XML comments.
12 /// </summary>
13 /// <remarks>
14 /// This class is a stand-alone class used to illustrate comments.
15 /// This particular XML comment is "attached" to the class as
16 /// a whole, while other XML comments are for fields or methods
17 /// in the class (a few methods and fields have been included for
18 /// illustration purposes).
19 /// </remarks>
20 public class Comments
21 {
22 /// <summary>
23 /// Here is a simple integer variable that is pre-set to the value 5.
24 /// </summary>
25 /// <remarks>
26 /// This is an instance member (non-static) of the class.
27 /// </remarks>
28 private int _five = 5;
29
30 /// <summary>
31 /// Here is a whole number that is pre-set to the value 0.
32 /// </summary>
33 /// <remarks>
34 /// This field is a static member of the class.
35 /// </remarks>
36 private static int _instanceCounter = 0;
37
38 /// <summary>
39 /// Here is a real number that is pre-set to the value 3.14159.
40 /// </summary>
41 /// <remarks>
42 /// This field is a constant member of the class.
43 /// </remarks>
44 private const double _PI = 3.14159;
45
46 /* ****************** Methods ******************** */
47 /// <summary>
48 /// This is a method of <see cref="Comments"/>
49 /// </summary>
50 /// <returns>This method returns a string.</returns>
51 public static string SimpleMethod()
52 {
53 return "Hello World!";
54 } // end of SimpleMethod()
55
56 /// <summary>
57 /// This is a one-sentence description of the method.
58 /// </summary>
59 /// <param name="name">This is where I describe the purpose of this para\
60 meter</param>
61 /// <returns>Here I describe what information is returned from this meth\
62 od.</returns>
63 /// <remarks>
64 /// This method has a single parameter.
65 /// </remarks>
66 public static int MethodWithParameter(string name)
67 {
68 return name.Length;
69 } // end of MethodWithParameter(string)
70 } // end of Comments class
71 }
Student
The Student class introduces a slightly more complex example by offering more fields.
- Data Attributes of the Student class:
- Name : String
- Gender : Character
- StudentId : Integer
- Program : String
- GradePointAverage : Double
- FullTime : Boolean
This example also includes two drivers. By using two drivers, this illustrates that separate “programs” can share/use the same class definition.
The first driver is a simple “test driver” to ensure that the class is “working”. This introduces the student to the idea that it is necessary to “test” or prove that the code we are creating is valid.
The second driver illustrates how the a single class can act as the basis for creating many distinct objects.
1 /**
2 * Purpose: To illustrate
3 * Highlights:
4 * - Keywords: char, int, double
5 * - Grammar: variable declaration (fields)
6 * - Other:
7 * - Instance members
8 */
9 namespace Topic.B.Examples
10 {
11 public class Student
12 {
13 public string Name; // The full name of the student
14 public char Gender; // Gender can be 'M' or 'F'
15 public int StudentId; // The school-provided student ID
16 public string Program; // The course program; e.g.: "CST"
17 public double GradePointAverage; // GPA is from 1.0 to 9.0
18 public bool FullTime; // If the student is enrolled full-t\
19 ime
20 }
21 }
1 /**
2 * Purpose: To illustrate
3 * Highlights:
4 * - Keywords: public, class, static, void, new
5 * - Grammar:
6 */
7 namespace Topic.B.Examples
8 {
9 public class DemoStudentDriver
10 {
11 public static void Main(string[] args)
12 {
13 Student bob, mary, joe, susan, frank;
14 bob = new Student();
15 mary = new Student();
16 joe = new Student();
17 susan = new Student();
18 frank = new Student();
19
20 bob.Name = "Bob McNalley";
21 bob.Gender = 'M';
22 bob.Program = "CST";
23 bob.StudentId = 200765789;
24 bob.GradePointAverage = 6.76;
25
26 mary.Name = "Mary McTavishski";
27 mary.Gender = 'F';
28 mary.Program = "CST";
29 mary.StudentId = 200765790;
30 mary.GradePointAverage = 5.76;
31
32 joe.Name = "Joe Jetson";
33 joe.Gender = 'M';
34 joe.Program = "CST";
35 joe.StudentId = 200765792;
36 joe.GradePointAverage = 4.66;
37
38 susan.Name = "Susan Orlando";
39 susan.Gender = 'F';
40 susan.Program = "CST";
41 susan.StudentId = 200765795;
42 susan.GradePointAverage = 8.54;
43
44 frank.Name = "Frank Smith";
45 frank.Gender = 'M';
46 frank.Program = "CST";
47 frank.StudentId = 200765797;
48 frank.GradePointAverage = 8.52;
49
50 displayStudentInformation(bob);
51 }
52
53 public static void displayStudentInformation(Student someStudent)
54 {
55 System.Console.WriteLine(someStudent.Name);
56 System.Console.WriteLine(someStudent.Gender);
57 System.Console.WriteLine(someStudent.Program);
58 System.Console.WriteLine(someStudent.StudentId);
59 System.Console.WriteLine(someStudent.GradePointAverage);
60 }
61 }
62 }
Employee & Company
The Employee and Company classes are similar to the Person and Student classes.
- Data Attributes of the Employee class:
- FirstName : String
- LastName : String
- SocialInsuranceNumber : Integer
- YearlySalary : Real
- EmploymentStartDate : Date
- Gender : Character
1 using System;
2 namespace Topic.B.Examples
3 {
4 public class Employee
5 {
6 public string FirstName;
7 public string LastName;
8 public int SocialInsuranceNumber;
9 public double YearlySalary;
10 public DateTime EmploymentStartDate;
11 public char Gender;
12 }
13 }
- Data Attributes of the Company class:
- Name : String
- City : String
- IsIncorporated : Boolean
- BusinessStartDate : Date
- NumberOfEmployees : Integer
- GrossIncomeToDate : Real
1 using System;
2 namespace Topic.B.Examples
3 {
4 public class Company
5 {
6 public string Name;
7 public string City;
8 public bool IsIncorporated;
9 public DateTime BusinessStartDate;
10 public int NumberOfEmployess;
11 public double GrossIncomeToDate;
12 }
13 }
In the following driver, the Employee and Company classes are both being used, illustrating the fact that any given “program” typically uses more than one class. In addition, this driver introduces the overloaded ToString() method in the DateTime class to improve the output of displaying dates and the Parse() method to convert a string representation of a date to an actual DateTime instance.
1 using System;
2 namespace Topic.B.Examples
3 {
4 public class DemoCompanyAndEmployee
5 {
6 public static void Main(string[] args)
7 {
8 Company Acme = new Company();
9 Employee Salesman = new Employee();
10 Employee Shipper = new Employee();
11
12 // Set the company's information
13 Acme.Name = "Acme International";
14 Acme.City = "Edmonton";
15 Acme.BusinessStartDate = new DateTime(); // new Date() defaults to t\
16 he current date
17 Acme.IsIncorporated = false;
18 Acme.NumberOfEmployess = 2;
19 Acme.GrossIncomeToDate = 2152368.52; // $ 2 million, plus change
20
21 // Set the salesman's information
22 Salesman.FirstName = "Wiley";
23 Salesman.LastName = "Coyote";
24 Salesman.Gender = 'M';
25 Salesman.SocialInsuranceNumber = 123456789;
26 Salesman.EmploymentStartDate = DateTime.Today;
27 Salesman.YearlySalary = 45250.00;
28
29 // Set the shipper's information
30 Shipper.FirstName = "Road";
31 Shipper.LastName = "Runner";
32 Shipper.Gender = 'F';
33 Shipper.SocialInsuranceNumber = 7777777;
34 Shipper.EmploymentStartDate = DateTime.Parse("June 1, 2008");
35 Shipper.YearlySalary = 54520.00;
36
37
38 // Show the information
39 System.Console.WriteLine("The information for the company:");
40 System.Console.WriteLine(Acme.Name);
41 System.Console.WriteLine(Acme.City);
42 System.Console.WriteLine(Acme.BusinessStartDate);
43 System.Console.WriteLine(Acme.IsIncorporated);
44 System.Console.WriteLine(Acme.NumberOfEmployess);
45 System.Console.WriteLine(Acme.GrossIncomeToDate);
46
47 System.Console.WriteLine("The employee information: Salesman");
48 System.Console.WriteLine(Salesman.FirstName);
49 System.Console.WriteLine(Salesman.LastName);
50 System.Console.WriteLine(Salesman.Gender);
51 System.Console.WriteLine(Salesman.SocialInsuranceNumber);
52 System.Console.WriteLine(Salesman.EmploymentStartDate);
53 System.Console.WriteLine(Salesman.YearlySalary);
54
55 System.Console.WriteLine("The employee information: Shipper");
56 System.Console.WriteLine(Shipper.FirstName);
57 System.Console.WriteLine(Shipper.LastName);
58 System.Console.WriteLine(Shipper.Gender);
59 System.Console.WriteLine(Shipper.SocialInsuranceNumber);
60 System.Console.WriteLine(Shipper.EmploymentStartDate.ToString("MMMM \
61 d, yyyy"));
62 System.Console.WriteLine(Shipper.YearlySalary);
63 }
64 }
65 }
Practice Exercises
- AnsweringMachine - Create the AnsweringMachine class so that it can provide a default answer for an incoming phone call as well as a customizable answer.
- Account - Extend the Account class from the example to include more information. Specifically, include an AccountType:String, BankName:String, BranchNumber:Integer, and InstitutionNumber:Integer.
- CanadianAddress - Create the CanadianAddress class so that it can represent the majority of possible addresses that some place may have in Canada.
- Course - Create the Course class so that it represents a post-secondary course.
- ExamResult - Create the ExamResult class so that it represents the results of an exam written by a student.
- LabResult - Create the labResult class so that it represents the results of a lab submitted by a student.
AnsweringMachine
The AnsweringMachine class provides a method to give an answer to an incoming phone call.
Problem Statement:
Create the AnsweringMachine class so that it can provide a default answer for an incoming phone call as well as a customizable answer. The methods should be named answer and they should return a String. There should be two methods in total, and both of them should be declared as instance members (non-static). The actual content of the default message can be whatever you choose, while the customizable method will receive a single String argument that has the name of the person receiving the message.
Also create a driver that demonstrates the AnsweringMachine in a Console environment
Create a driver for the AnsweringMachine class that creates an instance of the class and displays the results of calling the answer methods.
Account
Extend the Account class from the example to include more information.
Problem Statement:
Extend the Account class from the example to include more information. Specifically, include an AccountType:String, BankName:String, BranchNumber:Integer, and InstitutionNumber:Integer.
Also modify the driver to make use of the added information.
Notes
The branch number and the institution number together make up the Transit Number for a bank. “The bank transit number is 8 digits long. This is divided into a 5 digit branch number and 3 digit institution code, for example 10000-200.” (See http://en.wikipedia.org/wikiSort_code)
For more information on bank accounts and transit numbers in Canada, see http://en.wikipedia.org/wiki/Routing_transit_number#Canadian_transit_number.
CanadianAddress
This class represents an address for some place in Canada.
Problem Statement:
Create the CanadianAddress class so that it can represent the majority of possible addresses that some place may have in Canada. Design the class to have only public fields, as specified in this document.
- Data Attributes of the CanadianAddress class:
- Street : String
- Unit : String
- City : String
- Province : String
- PostalCode : String
- RuralRoute : String
- BoxNumber : String
Also create a driver for testing this class; you may use any name for the driver as long as it is not already mentioned in this package. In the driver, create instances of the CanadianAddress class that represent your current address as well as the address of your school (use hard-coded data).
Course
This class represents a post-secondary course with a theory (exam) and a lab portion.
Problem Statement:
Create the Course class so that it represents a post-secondary course. Design the class to have only public fields, as specified in this document.
- Data Attributes of the Course class:
- CourseName : String
- CourseNumber : String
- ExamCount : Integer
- LabCount : Integer
- ClassHours : Integer
Also create a driver for testing this class; you may use any name for your driver as long as it is not already mentioned in this package. In the driver, instantiate all of the first term classes you are taking and populate those objects with data (use hard-coded data).
ExamResult
This class represents the results of an exam for a student.
Problem Statement:
Create the ExamResult class so that it represents the results of an exam written by a student. Design the class to have only public fields, as specified in this document.
- Data Attributes of the ExamResult class:
- Name : String
- TotalMarks : Integer
- MarksEarned : Real
- ExamWeight : Integer
- StudentId : Integer
Also create a driver for testing this class; you may use any name for the driver as long as it is not already mentioned in this package. In the driver, instantiate all of the exams you have taken to date in this course and populate those objects with data (use hard-coded data).
LabResult
This class represents the results of an lab for a student.
Problem Statement:
Create the labResult class so that it represents the results of a lab submitted by a student. Design the class to have only public fields, as specified in this document.
- Data Attributes of the LabResult class:
- LabNumber : Integer
- TotalMarks : Integer
- MarksEarned : Real
- LabWeight : Integer
- StudentId : Integer
Also create a driver for testing this class; you may use any name for the driver as long as it is not already mentioned in this package. In the driver, instantiate all of the labs you have submitted to date in this course and populate those objects with data (use hard-coded data).