Answered step by step
Verified Expert Solution
Link Copied!

Question

00
1 Approved Answer

Part A: Create a Student class and add instance variables 1) Later we'll talk more about designing classes but for now, think about (1) things

image text in transcribedimage text in transcribedimage text in transcribedimage text in transcribedimage text in transcribedimage text in transcribed

image text in transcribedimage text in transcribedimage text in transcribed

Part A: Create a Student class and add instance variables 1) Later we'll talk more about designing classes but for now, think about (1) things that a university needs to know about students (these are its data attributes or characteristics that in OO programming are stored in what are called instance variables [We'll discuss why they're called "instance" variables later.1) and (2) things a student needs to be able to do (these are called methods). Instance variables and methods are the two main characteristics of every object like the student object we're getting ready to create. When we design objects we want them to be able to do something useful for us - those are the object's methods. And objects need to have information to do that work - those are the object's instance variables. Instance variables are how we capture and use information about the characteristics of an object that we care about. The characteristics of a student that a university might care about would include name, a student ID, age, gender, race, address, etc. Again, what the object "knows" are its instance variables, what it can "do" are its methods 2) Each instance variable is defined by its datatype and a unique name. Because instance variables are most often "things", we generally use nouns as instance variable names. Note that in Java the convention for variable names is what's known as camel case. That is, the first word of the variable identifier is all lower case letters. If multiple words are used in the identifier, the first character of every word after the first is upper case (like the hump on a camel). For example, a variable to hold your first name might have an identifier like firstName. A variable for the street of your address might just be street because it's only one word. A variable to hold your favorite movie might be named The table below shows the instance variable tables in the Student class STUDENT CLASS INSTANCE VARIABLES Instance Variable Description First name Student ID Gender Java Datatvpe String String char Java Identifier gender age Lives on campus 3) OK, now that you have some instance variables for your Student class, let's create this class in NetBeans. Create a new project called UnixersityDrixer. Make sure the Create Main Class box is checked and click Finish. 4) NetBeans will create a universitvdriverpackage and open a UniversityDriver.java source code file. 5) Expand the UniversityDriver project, right-click the Source Packages icon, click New, then click Java Class. In the popup, name your class Student (in the Class Name box). Click the Package dropdown arrow and select universitvdriver. Click Finish. Java creates this class, adds it to the universitydriver package, and opens the Student.java source code file. 6) The contents of the Student class are everything from the right of the opening curly brace that follows the word Student to the left of the closing curly brace two lines below. Those two curly braces define what's known as a block. Everything inside this block defines the Student class. One thing to get used to is that many Java constructs come in opening and closing pairs like parentheses (l and curly braces { ). Having a starting curly brace without a corresponding closing one or a closing one without the corresponding starting one will cause an error. It's easy to do when writing large amounts of code. To avoid this, if I type an opening parenthesis or curly brace I IMMEDIATELY type the corresponding closing one (NetBeans does this for you automatically). Then I set my cursor back between the two and carry on. Mark my words, you're going to hate yourself when you get one of these errors after you've written a couple of hundred lines of code and have to find the single parenthesis or curly brace that's not matched properly 7) Now start adding instance variable definitions to your Student class. Click the blank line below public class Student (. Type one line of code for each of the Instance variables in your instance variables table above. In Java, variables defined at the class level are called fields. To enter a field definition, type the datatype first then the identifier then a semicolon. For example, the definition for the irstName field would look like this: 10 *author Bruce 12 public class Student 13 14 15 String firstName: 1) Continue this until all your fields have been defined. 2) Let's try to create an object of the Student class. Type the following inside the UniversitvDriver main method: Student bob - newStudent ) Page 2 of 7 ITSC 1213 Lab 4 3) Student) is a special method called a constructor. Constructors are a required part of every class. Their purpose is to initialize the instance variables of an object as soon as it's created. There are a couple of important things to know about constructors They always have exactly the same name as the class. That's how you know they're a constructor. They don't have a return type. Constructors are required but you'll notice there's no method in our Student class named Student. That's because Java includes what's known as a default constructor. You can write your own constructors (we will do so in Part B) but if you don't, Java pretends you did and uses its own default constructor. . . 4) Let's print out the instance variables of bob by typing the following inside the main method: System.out.println (bob.firstName) System.out.println(bob.studentId) System.out.println(bob.gender) System.out.println(bob.age); System.out.println (bob. LivesOnCampus) Part B: Constructors 1) In Part A, we created a Student object using the default constructor, which initializes all of the fields to default values. When we create a Student object, we want to set the instance variables of that object - the fields - to values associated with the actual student this object represents. Since every student is different, we need a way to specify different values for each student. We're going to set up parameters in our constructor to do that for us. 2) In the Student.java, below the fields, let's add a constructor with the following parameters in the parenthesis: String fName, String ID, char studentGendex int studentAge, boolean isLiveOnCampus Remember that the constructor has the same name as the class, and it does not have a return type. Inside the constructor, assign the fields to these parameters. Page 3 of 7 ITSC 1213 Lab 4 3) Now that we're through defining how our constructor works, look what happened to the driver class. It has errors! Why? Because Java only provides a default constructor if no constructor is given. However, since we defined our own constructor now, the Student class does not have a default constructor any more. To fix this, you can add a default constructor to the Student class. Remember that the default constructor does not take any argument. Further, You may leave the body of the default constructor empty (still include the opening and closing curly brackets), and it initializes all of the fields to default values. After this, compile your project, the error message went away. You may run your program again, and it will give you the same output as before. 4) Let's try to use the constructor with parameters to create another object: Student john new student("John,, , 800123456", ,m,, 20, true); 5) Add some print statements at the end of the main method to print out all of the fields of object john. Does your constructor work properly? 6) When you have both Student constructors work, show the output to the instructor or TA to get credit for this part. SWITCH DRIVERS: whoever has been typing should now be navigating**** Part C: Getters and setters 1) Encapsulation, sometimes referred to as data hiding, is an important concept of object oriented programming. An object hides its internal data from code that is outside the class that the object is an instance of. Only the class's methods may directly access and make changes to the object's internal data. As a programmer, you can create a class definition, hide the fields and methods inside that definition, and set rules so that programmers who want to use your class have to follow the rules or be denied access. You can see how important something like this would be to deter hackers or to prevent accidental access to information. 2) In Student.java, let's add keyword private in front of all of the fields. Compile your project, you will see errors in the main method. This is because the fields are private now, and we cannot access them directly from a different class. How to fix this? This leads us to special methods called getters and setters. 3) More precisely, getters are technically known as accessors because they access data, and setters are known as mutators because they mutate or change data. We're going to use the getter/setter terminology. First, let's create some simple getters and setters for our Student class. 4) The convention for naming getters is the word "get" followed by the name of the field we're getting. The name for the firstName field getter would then be getFirstName, (Note how the method naming convention of camel case makes the getter method name just a tiny bit different from the name of the field we're getting.) Getters by their very nature must return some information to the calling program. The return datatype will be the same as the field's datatype. So the complete method definition for the getFirst Name method would be: public String getFirstName)( return firstName; Pretty simple, right? Typically, getters and setters are placed after the constructors although it's legal to place them in any valid location within the class definition. For consistency, let's follow that convention. 5) Now add a getter for each field in the Student class. 6) Fix the error in the main method by accessing each field for bob and john through the getter. 7) Setters are a little different because we're changing the value of the field, not finding out what's currently stored in it. This means that we need to provide a new value for the field. Normally we'll do that by passing in the new value as an argument. That means we have to define a parameter list for each setter method. Normally setters don't return a value so their return type is void. You do have to pass in some data and usually it's the same datatype as the field you're setting a new value of. Also, the naming convention for setter methods is the word "set" followed by the name of the field. Here's the setter for the firstName field, just copy it into your Student class: public void setFirstName(String fName) f firstName fName; 8) Now add a setter for each field in the Student class. 9) To ensure that our getters and setters work we should modify our driver class to test them Back in your nversityDryer class, comment out all the statements and add the following line: Student mary new Student ("Joan", "800234567", 'f', 19, false) : Add the following lines after the one above: Sytem.out println ("Object mary first name is " mary.setFirstName ("Sue" System.out.println ("Object mary first name is +mary.getFirstName ) "+mary.getFirstName 10) What's going on here? By entering mar FirstName (), we're asking Java to find the copy of the Student class file that belongs to the many object and call the getFirstName method that's stored there. If you'll look in the Student class definition you'll see that the getFirstName method returns whatever the value of that object's firstName field is. When we created the mary object and ran the constructor we entered Page 5 of 7 ITSC 1213 Lab 4 a value of "Joan" for the first parameter, the one associated with the firstName field. So until we change it, the mary object's firstName field will remain set to the string "Joan" 25 11) Next, we call the mar. setFirstName("Sue") method and pass it a value of "Sue". Inside the Student class definition we see that the argument value for that method is stored in the firstName field thus replacing whatever was there before. So the marv obiect's Name field value becomes "Sue". When we execute our third statement we retrieve the current value of the firstName field and print it out. If you run your program now you should see this (or something very like it): Object maxz first name is Joan Object mary first name is Sue 12) Here's the last point I want to make: I said that encapsulation is useful in keeping out hackers and preventing misuse of field data or object methods. But there's nothing in the code we ust wrote that would do such a thing. We won't go into these details right now but imagine if we changed the way those getters and setters were written so that unless you passed in the correct password as an argument, the method ignored you and didn't do anything? I didn't want to complicate the code by adding that kind of processing but you can see how that would solve the problem of unauthorized access 13) You can add more test statements if you want but for now, just add enough to show that one getter/setter in the each of the Student class works. 14) Show your Student.java and output to the instructor or one of the TAs to get credit for this part. ****SWITCH DRIVERS: whoever has been typing should now be navigating**** Part D: Add more fields and methods to Student class 1) To keep track of each student's balance on the 49er card, we are going to add a double type field balance to the Student class. Initialize this field to 0 in both constructors. 2) Add a getter method for the balance field. 3) We are not going to include a setter method for the balance field. Instead, we are going to provide the following two methods: . transferToCar paromCard 4) Start by creating the transferToCard method. This method allows Student object to transfer funds to their 49er card account. The bullet points below tell you what the method must do. public void transferToCard(double amount) o If the amount is positive, add the amount to the balance and print out the new balance. o Otherwise, print out an error message "The transfer amount must be greater than 0" 5) Now let's create the payEzomCard method. This method allows Student object to pay with their 49er card account. The bullet points below tell you what the method must do. public void payExomCard (double amount) o If the amount is less.than or equal to balance, subtract the amount from the balance and print out the new balance. o Otherwise, print out an error message "Sorry, your balance is too low!" 6) In the main method, add statements to test the newly added methods. 7) Add JavaDoc comments to each method in your Student.java. You may right-click the Source Packages icon, click Tools, then click Anaylze Javadoc. This will generate Javadoc comments for all of the methods, but you still need to add more information. 8) Generate the Javadoc for the Student class. Make sure that there is no error or warning

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions