Sunday, February 12, 2017

Creating Your First Java Eclipse Project




##########################################
[music].
Welcome to Dr. Piercy's Creating a First Eclipse Project By watching this video, you will learn how to start an Eclipse project You will learn how to add Java classes to your Eclipse project And, you'll learn how to run your project in Eclipse For this lesson, we're going to create the simple Java application illustrated by this UML class diagram. In this diagram, you see two classes depicted. This means that we'll create two Java files, one for each of the classes. One is payment, this will simply hold a main() method that will let us run the program. The more detailed class diagram is for the class called Person. and you can see in this class diagram that it will have three field level variables and then it will have several methods Note that there will be more getters and setter than are listed in this diagram these were just abbreviated for brevity :-) Please keep in mind that in this lesson we're really concentrating on how Eclipse can be used to create classes. We will save more detailed discussion of actual Java code for later lessons. We'll start with Eclipse open in the basic perspective. To start a new project, recall that you go to File menu and you choose the New option. Then, you look for Java project. Note, that on mine it's listed here. If you do not see it, you can always go to Other. And in Other, you can search and browse until you find the type of things that you are interested in creating. In this case, we are creating a basic Java project. Whether, you went from the original menu or through the Other dialog you'll still get to the same page after I hit Next. Keep in mind that you generally want to review carefully and fill out carefully all of the dialogs when creating an item in Eclipse because this will make sure that it's created right the first time. For this page, it's the simplest type of process. So, we are going to simply type in the project name. We'll call it EmployeePayment [music and typing].
And, for the rest of the items on the page we will accept their defaults. For a quick look at the next page, click Next. We will see that we are going to have the EmployeePayment project level, and then below that in the hierarchy there will be a folder called "source" (src) and this is where are Java classes are going to go. Once, you accept this hit finish. And, your project is created. You can explore it over in the Package Explorer by expanding the project by just clicking on the arrow to the left. You'll notice that we have a src folder for our Java classes and our basic JRE system library. Recall, that we are going to create two classes. A Payment class and a Person class. Since the Person class is required in order for the payment class to do its thing we are going to create the Person class first. Also, most of the work is in the Person class as we can see by this UML class diagram. We're going to start by creating the class. Then, we'll ad the fields. Remember, the focus is on how we do this in Eclipse and not necessarily on the Java code. So, I'm going to talk about Java things minimally and focus on Eclipse. When we created our EmployeePayment project, we went to the File|New menu option. Generally, I prefer that when I'm creating new objects that go into or are contained within a project to basically start from the Package Explorer and right-click on the folder where I intend to put the item that I am going to create. In this way, I get the benefit of the location automatically being placed within the dialog. So, right-click on src folder and choose New. And, from the list, you should see Class. If you do not see it here, go into Other and browse for the Class item. Again, because we are creating something new, we see a dialog form. Be sure to always look at everything on the form. Check that it's what you want and change those that need to be changed. In this case, I am going to simply change the name of the class. I'll call it Person. I'm going to leave the modifier "public." I right-clicked on the src folder to put it where I wanted it to be. Note, also, that there is a message stating that the use of the default package is discouraged. In general, it is better to create packages to organize your items. Note, the super class, it inherits from the java.lang.Object which every class that you create in Java will inherit from. In this case, I do not need a main(). That will be in the other class that we will create. I can just take the defaults for everything else. Click finish, and you will see in just a moment that your class will appear in the editor section of Eclipse. Now a Java class is probably the simplest thing that you can create in Eclipse. So, the code that is generated based on the form that you fill out is very minimal. There is not much there. Simply, the public class Person \{} to indicate that this is a class. As you'll see, there are some very nice options that you can use in Eclipse to create this Java class very quickly. We must start, though, by identifying the fields that we will put. Let's take a quick look back at our UML class diagram to remind ourselves what we need to create. We are going to have firstName, which is a String. lastName field, also a String. And, an hourlyRate, which is double and this would be the amoung of payment that each Person will be paid for each hour worked. Back in Eclipse in the editor, we see that items typed into the editor are color-coded. Java keywords are kind of purple on my screen. Place the cursor inside the Java class (between the \{}) We'll start by declaring our firstName String. So, in general, to enter things into the Eclipse editor place the cursor where you want it and start typing. You'll notice several things in the editor such as the underlines. Underlines to give you warnings. If it's yellow it's generally a warning that "Hey, there may be some problem." that's noticed by the editor. In this case, no real problem. I've declared this variable, but I have not yet written anything to use it. So, it's warning me that it may never be read. We'll fix that when we add methods. As I've added the second one, I'm going to pause for a moment to show you how an error message appears in the editor. Notice that this is underlined. In this case, I've simply left of the semi-colon. If I put the cursor over the underlined in red item, an error message will appear. In this case, it tells me "Syntax error - insert the semi-colon to complete the field declaration." I do that, and I see that the error disappears. Let's enter the last one which will be double. It will be the hourlyRate. Notice, also, that I am following Java naming conventions. A convention is a standard way for naming things that everyone in the profession will use and that makes it easier for people who are used to Java to read your code; for your later to identify the difference between variables and classes; and many other things related to code generation. So, stick to conventions as much as you can. This convention is known as "camel case." The idea for variables is that you always start with a lower case letter on the first word of the variable name. If there are multiple words in your variable name we will concatenate - bunch them up together - and then any successive word will start with an upper-case letter. For classes, we follow similar rules but the first letter is capitalized. So, you can see that Person is a class very quickly and firstName is a variable because I have followed standard naming conventions. Let's revisit our UML class diagram. to remind ourselves what we need to do next. In general, a class diagram is a blueprint for what we want to create. So, we can see that, so far, we have created three of the items on our list: the firstName the lastName field; and the hourlyRate field. Next, let's work on the constructors. As you can see, we have two constructors. One called Person() that takes no arguments. The second called Person(String, String, Double) The first one will be our default constructor which we'll use to initialize our field variables to default values. The second one will allow someone who uses the class to actually enter in values for the firstName, lastName and hourlyRate as soon as they begin creating an object of the Person class. Back in Eclipse, we see that we have our class with the three fields declared. Let's look at a nice feature of Eclipse that will let us create a constructor very quickly. Click on the Source menu. Notice that there are 4 or 5 or 6 lines down the Source menu that start with the word Generate. "Generate Getters and Setters" and so forth. Let's select the one that says "Generate Constructor Using Fields." These code generation features let us create very quickly some of the most common elements of a Java class by simply filling out a form. We can use this one to create a constructor using fields or, if we deselect them all, make a constructor that does not use the fields. Let's do this one first. This will be our default constructor. I'm going to deselect them all. I;m going to check my insertion point, so that I put it where I want in the class. In this case, it will be after my hourly rate. Or, I can also click here and choose to put it "after the last member" I generally find this to be safest, because I do things in a certain order and I know it's going to be at the end of the class. But, if you forget something and want to place it, you can choose exactly where you want from this list. We'll leave everything else as default. Always check on these forms to make sure that it's what you want in any particular case. Once, you have the form filled out, hit OK Notice, it's created some code for us. It added some comments. And Eclipse has also created the stub for our default constructor. As I mentioned, I'm going to simply use this constructor to set default values for my field level variables. Let's start by typing the word "this" "this" is a keyword that refers to this Java class. Right after the word "this", hit the period. Another nice feature of Eclipse is once you have an object that can be identified if you hit dot (or period) Eclipse will "look ahead" and it will try to figure out what you want next. And, it will pop-up a menu that will show you the options that you have. In this case, notice that my fields are the first three items on the list. So, I'm going to highlight the firstName. Double-click it, and it pops up into the space there. And, now I can do "=" let's say "John".
Let's do the same thing for lastName. "this." Select lastName from the list "= Doe".
Now, you've got to be careful with the period. If you keep typing, "this.lastName" you'll probably pass by the menu very quickly without seeing it. So, it's up to you whether you want to utilize that function. It's usually best to hit the "." and then pause. I think to reduce errors it's better to use the menu because you know that you're going to have exactly what was declared in your variable declaration statement above without mistyping. We'll get the hourlyRate, and let's set that to "10; dollars..
Okay, very quickly our first constructor has been created. Let's use the same feature to construct or to create our second constructor. So, this time, pick generate constructor using fields. This time however, let's leave all of our fields checked. Everything else - we'll double check those. Let's make it the last member to come at the end. Select "public", choose all of these. And then, let's select "OK" Now, we're cooking! Look at this constructor. All of the lines have been created for us. If, somebody uses this constructor they will provide the firstName, lastName and hourlyRate as inputs to the constructor. And then, the lines for setting our field variables will set each field variable equal to the values that were passed in through the method parameters. Just a reminder, having two or more methods with the same method name as we do with these constructors is called overloading in Java terminology. At the moment, we have a significant amount of text in our class. So, one thing that I like to frequently do is to simply click on the "Save" button in the icon bar in order to make sure it's saved. This is something that you should just frequently get in the habit of doing. Every once in a while, add a little code, then save. Let's have a quick look at our UML class diagram again. Now we have 5 items created. Let's work on the getters and the setters for our Person class. Back in Eclipse, you might recall that when we went to the Source menu there were a number of "Generate..." options. and one of those was "Generate Getters and Setters." Let's use that to create at one fell swoop the getters and setters for all of our class level field variables. Click on "Generate Getters and Setters." Note that you can select all of them. You can deselect all. You can select just a "Get" for a particular field. Or, if you hit the top level of the hierarchy you can select both the get and the set for a particular field. I'm going to select all. Double check the insertion point. I prefer to have fields in getter/setter pairs for instance, getFirstName() and setFirstName() will be together in my class You have other options. You can do all of the getters together, then all of the setters together if you prefer. These will be public. I'll generate method comments even though at this point I may not enter many comments. Then, I'm going to hit "OK." So, click "OK" and watch what happens to the Person.java file that you are creating. Look at that! Very quickly, by selecting a menu option, filling out the form, we've created very basic getters and setters for our class..
This means that basically we have only two more methods to create to finish the Person class. Another quick look at our UML class diagram and we se that we are almost finished. We still have left he getPayment() method and the toString(). I'm going to skip to the toString() because we have yet one more "Generate..." that we can use to create the toString(). And then, we will work on the getPayment(). So, back in Eclipse, click on "Source." Go to "Generate..." and this time pick "...toString()" The toString() method is generally a method that you can use when if called it will return a String that shows the name of the class and the current state of the class, meaning the variable values of the fields. You can have it show much more if you select those, but I'm going to just select the fields, make sure it's inserted as the last member generate some comments, I'll take the default String format. You can actually format that anyway you want. We'll choose code style as "String concatenation." This changes what is generated. Play around with that if you'd like to see it another way. Then, I'll keep the defaults for everything else. Click "OK".
And now you see a toString() method. When toString() is called a String that shows what the current values of firstname, hourlyRate, and lastName will be provided. We'll use that in our main() method in a little while. Finally, I have one more method to create. This is our getPayment() method. For the getPayment() method I will have to provide a number of hours as an integer and then I will return the payment as a double. This is the only method in this class that I am going to have to type. ... public ....
... double ....
... getPayment( ....
.. int ....
I'll call it "hours" because we are going to provide hours. Notice, that at the moment, I have an error. Although, I'm quite confident in the code as written. Let's see what the error message says. Recall that you put the cursor over top of either the underlined portion or over in the margin. You'll see that "This method must return a result of type double. Also, you notice that there are quick fixes available. This error, of course, is because I have not yet written a return statement and in my method stub.
I have shown that I need to return something that is double. When I put the cursor over the error message, if I want to use one of the quick fixes, I have to be careful and know what they are, but eventually you learn that for certain errors there is often a list of things that you can do to correct it. Once you know what needs to be done at that point Add a return statement or change return to void you can intelligently pick from the list. Double-click on "Add Return Statement" Look at that! It placed a return statement in my method. There error is gone. Now, this return statement is not exactly what I need. And here is one of the dangers of choosing from that list. Eclipse will try to assume that you need to return something it knows about. And in this method, the only local variable that it knows, is the hours that we've declared as an argument for the method. So, it assumes that the thing you want to return is the only thing it knows about called "hours." But, this is incorrect. I need to calculate a payment. Let's clean up a couple of spaces here. Let's take out hours. What we are going to return is going to be the "hourlyRate." Remember, I can type "this." and then choose "hourlyRate." times the "hours.".
This will multiply hourly rate times hours and return the result. Now anytime someone calls getPayment() they provide how many hours and you get the amount of payment for the week. Click on "Save" to save our Person class..
One last look at our UML class diagram shows us that to run our project we need to create a Payment class. Inside the payment class, we will create a main() method. A main() method is required by all Java programs This is where, when you say "Run" for the program it's the code in the main method that will run to get it started. So, once again, let's get to Eclipse and let's start creating our main class..
Right-click on the folder that we are going to put the class in. Select "New", then "Class." We are going to name this class Payment. Double check everything. We are going to take the defaults from pretty much everything else on this form except, let's select "public static void main()" in order to make sure that the main() is generated. Do that and hit "Finish" Payment was created and it created a stub for our method called main(). The "ToDo" comment is pretty nice. It's a feature in Eclipse that I'll show you later but it will look at any comment called "ToDo" and will have a nice "ToDo" list we can see in one of the tabbed areas at the bottom. For now, let's just.
Erase that comment.
And let's do something that we might like to work with with Person. I'm simply going to.
Create a Person object. [music and typing.
I'll use the default constructor for this one. If I do that, I'll want to set firstName (setFirstName()) Notice that I hit "." after typing Person. And, I can then.
Type a letter if I want to narrow the field of what's listed. And, then I see that I can set lastName (setLastName()) Finally, I can.
Set the hourlyRate (setHourlyRate()). Let's just make that $10 per hour. We are going to basically want to create a Person object and print results to the console. The console is the area at the bottom of your Eclipse perspective. And this will show you the basic output or your program. To do that, I would use the "System.out.println()." The default "out" for your Java class in Eclipse is the console at the bottom of the Eclipse perspective. Well, let's see that my class has been created correctly by calling the "toString()" method to print that out..


##########################################

No comments:

Post a Comment