tutorial

Java Lesson 05 – Inheritance

In this lesson we are going to continue with the classes from the last lesson. Do create a new project called Lesson 05.

Object instances

Look at the following code. What do you expect the System.out.println to print out? Now run the code. Where you wrong or correct? Why do you think that happened?

With the Animal b = a; you give b a reference to a, making both a and b point toward the same Object instance. So when you change a, b will also change.

Now look at the following code and try to guess what will happen again and try it out.

When a gets a new instance that doesnt mean b will also get a reference to that new instance. The b object will keep having the Miranda instnace that’s later renamed to Miranda.

Like I’ve said before all classes inherit the Object class this means any class can be cast to Object without any problems.

Inheritance

To make one class inherit another class you use the extends keyword. Now lets create a Horse class which inherits the Animal class. In this class also @Override the getType functions and directly return the correct type, so they dont have to be set anymore.

Now you should change the Animal class to an abstract class, because when you need Animal classes they should just create seperate classes for them.  You can also delete the setType function as that shouldnt be used anymore and change getType into a abstract function that should be overriden by classes that extend Animal. So far we used the toString() function to print out our animals, we are now going to create a print function in Animal instead.

An abstract function can not have any functionality so it doesn’t have curly brackets. Abstract can only be created in abstract classes and when a class inherits an abstract class it will be forced to create all abstract functions in that class otherwise it will give errors. Give it a try by creating a Cat class which extends the Animal class. Also give this class two new functions isClipped that returns a boolean and a setClipped which sets if the cat has been clipped. Also @Override the print function to print out whether or not the cat has been clipped.

Result SelectShow

Now if you create an instance of the Cat class and print it, it will show whether or not your cat has been clipped.

<h2>Assignment</h2>
Create two new functions in the Animal class called setAge and getAge. These functions will take an int. Also create an abstract function called getAverageAge with an int as return type. Next create some more animals and like the cat try and think of unique functions and variables to give them and override the getAverageAge and getType correctly in them.
<h2>Download</h2>
The examples and the solutions to the Assignment you can <a href=”https://dl.dropboxusercontent.com/u/3096920/tutorials/java/Lesson%2005.zip”>download here</a>

Java Lesson 04 – Classes

Classes

A big part of learning how to program, is knowing how to use and create classes. So far we have already seen a couple of classes: System and Scanner. These are all classes included with java. Things that weren’t classes were int and double. Those are primitives.

Classes in general start with an Uppercase and each subsequent word is also capitalized, example: InputStreamReader. When you initialize a class you always use the new keyword: Scanner scanned = new Scanner(). Primitives on the other hand can be directly initilized: int i = 10;

Now let’s create our first class. Create a new project and call it Lesson 04. In the project right click the src folder -> New -> Class -> name it Animal (make sure public static void main(String[] args) is unchecked) -> press Finish. An Animal.java should have been created now with the following code inside:

The keyword class is used to create a class and public means that it can be used by other classes, it’s publicly available. The name of the class is Animal and should be the same as your .java file. Everything between the {} will be part of your class. Something that you will also need to know is that all Class inherit the Class Object. This means that all classes are of the Object type.

Next just like the previous lessons create a Main class where you initialize our Animal class:

In this line the Animal horse = is where you create a new Object called horse with the class type Animal. With = new Animal(); you initialize your Animal Object called horse with the class Animal. So to initiate a new class the syntax is: <class type> <initialized object name> = new <class type>(); . What the round brackets are for at the end we will go over later.

When you run this it will print out something like: Animal@e53108, which is basically <class>@<hash>. The hash is used by the compiler and you will probably never have to do anything with that. This print out doesn’t really tell us enough. We want it to print out that its a horse, but so far our Animal class doesnt know its a horse yet.

So lets first create two functions: One to set the type of the Animal class and One to get the Type.

Lets first create the function that will set the type of our Animal.

Here we created a function called setType which takes one parameter that is of the type String.

Next create a function that will get the type from our Animal.

The getType doesnt need any parameters, but it does have a return type and it’s a of the type String. If a class doesnt have a return type it will be called void, like the setType function.The syntax to create function is basically: <plublic/private> <return type> <function name>(<parameters>){}

The getType function is probably also give you an error, because it has a return type defined but its not returning anything, we will fix that next.

To actually make the class remember it’s type we will need to create a class variable. At the top of you class (inside the {} ) place:

So if your Animal object doesnt have a type set, it’s default type is None. To make the setType function set the class variable instance add: this.type = type; to it. To make the getType return the type add return type; to it.

Result SelectShow

The this. in the setType is to reference the class variable. In  the setType function there are two variables with the type name, the one that is given when the function is called and the class variable. When you put your cursor on the type variable it should highlight where it’s being used. The keyword this is used to call the current instance of the object and call its variables or functions, it’s not always necessary to use, but to make the distinction between the class variable and the one given it is in our case.

Now to change what the Syste.out.println prints out we will need to override the toString function of the Object class which all class inherit. This function has a String as return type. In this String we are going to return our type.

Above this function you see @Override. This is an annotation. This annotation is used to tell the compiler is overriding a function that it inherited from another class. Basically this means that it will just throw an error if it’s trying to override a function that doesn’t exist yet. Try change the function name to tooString for example. It will give you an error, because that’s a function it doesn’t know. The same thing if you try to change the return type to something else.

Now when you run the following code in your Main class:

It should print out: Animal type= Horse and Animal type= None.

Assignement

The assignment is to add a name and weight to the Animal. So create a setName and getName, the name is a string. Also create a setWeight and getWeight and weight is a double. Finally change the toString function to also display the name and weight of the animal. To test if everything is working create 10 animals with different values.

Download

The examples and the solutions to the Assignment you can download here

Special note

A String is also a class, not a primitive, even though you don’t need to use new to initialize it. String is an odd one in this. Because String is a simple class and it’s used a lot, java added a way to optimize memory use. When you create two different strings with the same value, they will have the same reference in your memory. You can call new String as well to give a new reference, that is why when comparing Strings you should always use equals, which checks if the values are the same.

 

Java Lesson 03 – User input / Ifs

User input

Now that we had some of the basics lets do some ‘real’ programming. We’ll start with something simple: accepting user input. As with everything there are multiple ways of doing this. We’ll do it with the Scanner class. The Scanner class is a java class used to get user input lines in the console. The constructor of the Scanner class needs an InputStream. This means that to create a Scanner object an InputStream object is needed. In our case to ‘listen’ to what the user is typing we will use the System.in. This will give us the InputStream of the system, which is in the console.

Lets try that with an example. Create a new project called Lesson 03, create a Main class and copy in the following code:

When you copy this code in and press ctrl + s, to save, there will be a red line under Scanner meaning it has an error. This is because it doesnt recognize the class Scanner. To fix this we need to import it into our Main class. An easy way todo this is to stand with your cursor on the error and hit ctrl + 1 (or right click and press quick fix), this will bring up the quick fix menu. In this menu you should be able to choose to create your own Scanner class or to import the existing java.util.Scanner class. Choose to import and hit ctrl + s again to save. Now you shouldnt have any errors left. (I wont be telling you to save again, you need to save your code to run it and you need to save it for eclipse to compile and check if you have errors)

When you run this program it will say Firstname: and then pause. Now put your cursor in the console and type your first name. When you hit enter the program will continue and ask for your lastname. Fill it in and hit enter again and it will print out your full name.

As you might have guessed scanner.nextLine() will pause your program and wait for you input and when you have have typed something and have pressed enter it will put what you typed in the lastname String. How it does this I dont know. All I know is that it listens to the InputStream we gave in the Scanner constructor. Its kind of like using a tv. We know how to turn it on and we know how to change channels, but we dont know how it does this. Same goes with many java classes. You dont have to know how they do it, you only need to be able to work with them.

If Statements

The programming we have done so far is pretty liniar. Most of the time you will want certain pieces of code only to execute when a certain comdition is met. (.lenght() gives the number of characters in a String)

Those are all the basic ifs. Now the firstname and lastname program we had and print out a message if they are shorter than 3 characters or longer than 16. Do this in 4 different ifs and try to use 4 different conditions.

Result SelectShow

Our current program has 4 ifs it will always check, which isnt really necessary. If firstname < 3 is true it will still check if firstname > 16 too. You can improve this with an if else construction.

Assignment

Besides making it ask for lastname and firstname make it also ask for your adress, city and phonenumber. Also create an integer error that tracks how many things are filled in wrong. If there were no errors print out that everything was filled out succesfully.

Download

The examples and the solutions to the Assignment you can download here

Java Lesson 02 – Numbers

Learning about numbers

In the previous lession you learned about the Object type String used to contain text. In this lession you will learn about the various object types that can hold numbers.

We will start with creating a new project. Calls this project Lesson 2. After that create a Main class again, just like in the previous lesson. If you forgot how to do that look it up in Lesson 1.

The most used types for numbers are Integer and Double. Lets start with Integers. An Integer is most often refered to as an int. Integers are always whole numbers with no decimals.

Try the following example:

As you can see in the example above an int can be converted to a double, but a double cant be converted to an int.

Basic Calculations

Lets start with some basic calculations answers are down below, but try solving them yourself first before looking at the answers.

Some basic math first. Remember it is * / before + –

Answers SelectShow

Next some calculations with round brackets. Calculations inside round brackets go first.

Answers SelectShow

When calculating with double and ints make sure to watch out what you are calculating with, because ints are whole numbers and always rounded downwards. Again, guess what the answer will be and figure out why that is.

Answers SelectShow

Now you might be wonder what the use of integers are and why not just use doubles for everything. For 1 integers take up less space in your memory and for al lot of calculations double just isnt necessary as you will see in coming Lessons. For now its just important that you know the difference between the two.

Assignment

You have 3 numbers 8, 3, 2 you can choose yourself whether you use them as a double or integer. You can use each number only once and you need to use them all.

Try get the following results:1) 9.0
2) 3
3) 2
4) 12.0
5) 7
6) 1.0
7) 4
8) 5

Answers SelectShow

Download

The examples and the solutions to the Assignment you can download here

Java Lesson 01 – String basics

Creating a new Project

note: everything about programming is case sensitive make sure to use the right case.

In eclipse at the top right click File -> New -> Java Project. You will now have a New Java Project wizard. Fill in the Project name: Lesson 1 and press finish. Is that it? What about the other options? Don’t worry about the other options for now. It’s all fine. You now have created your first project.

Ok so now you might be wondering thats nice and all, but what is it for? A project is the shell of your programm. Its the container of your class files. In it self it does nothing. Its mostly made to make your improve your workflow and keep things organized. Lets continue into making this project a runnable program.

Go into your Lesson 1 project and right click the src(source) folder -> New -> Class. This will open up a New Java Class wizard. Fill in the name: Main and put a tick infront of public static void main(String[] args). When you’ve done that press Finish.

Inside your src folder should now be a (default package) and inside that a Main.java. For now you can ignore the (default package) we’ll go into packages later on you can ignore that for now. Open the Main.java and you should see:

Everything that starts with // or is inbetween /** and */ are comments, remove these for now. Now than lets starts simple and add to the main:

Ok let me explain this piece of code. String s = “Hello World!”; is how you define a variable. String is the variable type, s is the variable name and “Hello World!” is the variable value. And in java you have to end every line of code with a semicolon. Strings are used to store text in, values of a String variable have to be inbetween double quotes. The s is a variable name you can basically call it whatever you want as long as its not a known variable type, something like String String = “Hello World!” would give you errors also variable names have to start with a letter and may only contain letters, numbers or underscores, so no spaces or starting with numbers. There are more variable type, we’ll get into them later.

The System.out.println(); is javas way to print stuff to the console. In the above sample we will be printing the String s. Its not really something you need to understand, just know how to use it. Its mostly used to debug your code.

Now lets teach you how to run this. Before running your code you always need to save your code, use ctrl + s. You should save quite often, because after you save it recompiles internally and shows you if you have any errors. What happens if you run your code is that it compiles and runs your code. Eclipse does this all automatically for you.

There are multiple ways to run your code:

  • Right click Main.java -> Run As -> Java Application
  • Select the Main.java and hit the Green circle with an arrow inside in the eclipse toolbar
  • Select the Main.java and hit ctrl + F11
  • Select the Main.java and go to Run -> Run in the eclipse top menu bar.

After you’ve run it, your console log should dsiplay that is was <terminated> and there should be Hello World! in the log. Congratulations you have now created your first program.

Playing with strings

This bit is where you get to try out code yourself. What do you expect the results of the following pieces or code are? Be sure to try them out one by one.

Besides System.out.println there is also System.out.print which prints everything on the same line.

Read after trying out all the examples SelectShow

Assignement

This assignement is optional. You can move on to the next Lesson if you want.

Assignment: Create me some ASCII Art. Before you ask me what ASCII Art is do some research yourself, it’s pretty easy to find out.

Warning: Try not to use a \ in your string it will give you errors. If you want a \ you will have to do a double \\. Ill explain why that happens some other time.

Download

If you want my project with the Hello World and my ASCII Art download it here.

Unzip it somewhere on your pc, not in your workspace. In eclipse: File -> Import -> General -> Existing project into workspace -> Browse to where you stored the Project -> Tick copy into your workspace -> Press finish.

You can now delete where you stored the project.