24
Learn Java Programming Learn Java programming tutorial lesson 1 - First Program Learn Java programming tutorial lesson 2 - Variables and constants Learn Java programming tutorial lesson 3 - Decisions Learn Java programming tutorial lesson 4 - Loops Learn Java programming tutorial lesson 5 - Data input and type conversions Learn Java programming tutorial lesson 6 - Arrays Learn Java programming tutorial lesson 7 - Object-Oriented Programming(OOP) Learn Java programming tutorial lesson 8 - Inheritance Learn Java programming tutorial lesson 1 - First Program What is Java? Java is an object-oriented programming language which was developed by Sun Microsystems. Java programs are platform independant which means they can be run on any operating system with any type of processor as long a s the Java interpreter is available on that system. What you will need You will need the Java software development kit from Sun's Java site. Follow the instructions on Sun's website to install it. Make sure that you add the java bin directory to your PATH environment variable. Writing your first Java program You will need to write your Java programs using a text editor. When you type the examples that follow you must make sure that you use capital and small letters in the right places because Java is case sensitive. The first line you must type is: public class Hello This creates a class called Hello. All class n ames must start with a capital letter. The main  part of the program must go between curly brackets after the class declaration. The curly  brackets are used to group together everything inside them. public class Hello {

Learn Java Programming

Embed Size (px)

Citation preview

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 1/24

Learn Java Programming

• Learn Java programming tutorial lesson 1 - First Program• Learn Java programming tutorial lesson 2 - Variables and constants•

Learn Java programming tutorial lesson 3 - Decisions• Learn Java programming tutorial lesson 4 - Loops• Learn Java programming tutorial lesson 5 - Data input and type conversions• Learn Java programming tutorial lesson 6 - Arrays• Learn Java programming tutorial lesson 7 - Object-Oriented Programming(OOP)• Learn Java programming tutorial lesson 8 - Inheritance

Learn Java programming tutorial lesson

1 - First Program

What is Java? 

Java is an object-oriented programming language which was developed by SunMicrosystems. Java programs are platform independant which means they can be run onany operating system with any type of processor as long as the Java interpreter isavailable on that system.

What you will need 

You will need the Java software development kit from Sun's Java site. Follow theinstructions on Sun's website to install it. Make sure that you add the java bin directory toyour PATH environment variable.

Writing your first Java program

You will need to write your Java programs using a text editor. When you type theexamples that follow you must make sure that you use capital and small letters in theright places because Java is case sensitive. The first line you must type is:

public class Hello

This creates a class called Hello. All class names must start with a capital letter. The main part of the program must go between curly brackets after the class declaration. The curly brackets are used to group together everything inside them.

public class Hello

{

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 2/24

 

}

We must now create the main method which is the section that a program starts.

public class Hello

{public static void main(String[] args)

{

 

}

}

The word public means that it is accessible by any other classes. static means that it isunique. void is the return value but void means nothing which means there will be noreturn value. main is the name of the method. (String[] args) is used for command line parameters. Curly brackets are used again to group the contents of main together. You probably won't understand a few of the things that have just been said but you will know

what they mean later on. For now it is enough just to remember how to write that line.

You will see that the main method code has been moved over a few spaces from the left.This is called indentation and is used to make a program easier to read and understand.

Here is how you print the words Hello World on the screen:

public class Hello

{

public static void main(String[] args)

{

System.out.println("Hello World");

}}

Make sure that you use a capital S in System because it is the name of a class. println is amethod that prints the words that you put between the brackets after it on the screen.When you work with letters like in Hello World you must always put them betweenquotes. The semi-colon is used to show that it is the end of your line of code. You must put semi-colons after every line like this.

Compiling the program

What we have just finished typing is called the source code. You must save the sourcecode with the file name Hello.java before you can compile it. The file name must always be the same as the class name.

Make sure you have a command prompt open and then enter the following:

javac Hello.java

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 3/24

If you did everything right then you will see no errors messages and your program will becompiled. If you get errors then go through this lesson again and see where your mistakeis.

Running the program

Once your program has been compiled you will get a file called Hello.class. This is notlike normal programs that you just type the name to run but it is actually a file containingthe Java bytecode that is run by the Java interpreter. To run your program with the Javainterpeter use the following command:

java Hello

Do not add .class on to the end of Hello. You will now see the following output on thescreen:

Hello World

Congratulations! You have just made your first Java program.

Comments

Comments are written in a program to explain the code. Comments are ignored by thecompiler and are only there for people. Comments must go between a /* and a */ or after //. Here is an example of how to comment the Hello World program:

/* This program prints the words Hello World on the screen */ 

public class Hello // The Hello class

{

public static void main(String[] args)// The main method 

{

System.out.println("Hello World");// Print Hello World 

}

}

Learn Java programming tutorial lesson

2 - Variables and constants

What is a variable

Variables are places in the computer's memory where you store the data for a program.Each variable is given a unique name which you refer to it with.

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 4/24

Variable types

There are 3 different types of data that can be stored in variables. The first type is thenumeric type which stores numbers. There are 2 types of numeric variables which areinteger and real. Integers are whole numbers such as 1,2,3,... Real numbers have a

decimal point in them such as 1.89 or 0.12.

Character variables store only 1 letter of the alphabet. You must always put the vlaue thatis to be stored in a character variable inside single quotes. A string variable is like achracter variable but it can store more than 1 character in it. You must use double quotesfor a string instead of single quotes like with a character.

Boolean variables can store 1 of 2 values which are True or False.

Here is a table of the types of variables that can be used:

Name Type Values byte Numeric - Integer -128 to 127

short Numeric - Integer -32 768 to 32 767

int Numeric - Integer -2 147 483 648 to 2 147 483 647

long Numeric - Integer -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807

float Numeric - Real -3.4 * 1038 to 3.4 * 1038

double Numeric - Real -1.7 * 10308 to 1.7 * 10308

char Character All unicode characters

String Character All unicode characters

 boolean Boolean True or False

Declaring variables

You can declare a variable either inside the class curly brackets or inside the mainmethod's curly brackets. You declare a variable by first saying which type it must be andthen saying what its name is. A variable name can only include any letter of the alphabet,numbers and underscores. Variable names can start with a $ but may not start with anumber. Spaces are not allowed in variable names. You usually start a variable name witha lower case letter and every first letter of words that make up the name must be upper case. Here is an example of how you declare an integer variable called MyVariable in themain method:

public class Variables

{

public static void main(String[] args)

{

int myVariable;

}

}

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 5/24

If you want to declare more than 1 variable of the same type you must seperate the nameswith a comma.

public class Variables

{

public static void main(String[] args)

{int myVariable, myOtherVariable;

}

}

Using variables

A = is used to store a value in a variable. You put the variable name on the left side andthe value to store in the variable on the right side. Remember to use quotes when storingString values. You can also store a value in a variable when it is declared or later in the program.

public class Variables

{

public static void main(String[] args)

{

int myInteger;

myInteger = 5;

String myString = "Hello";

}

}

You can print variables on the screen with System.out.println.

public class Variables{

public static void main(String[] args)

{

int myInteger = 5;

String myString = "Hello";

System.out.println(myInteger);

System.out.println(myString);

}

}

You can join things printed with System.out.println with a +.

public class Variables{

public static void main(String[] args)

{

int myInteger = 5;

System.out.println("The value of myInteger is " + myInteger);

}

}

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 6/24

Variables in calculations

The important thing about variables is that they can be used in calculations. When you perform a calculation you must store the result in a variable which can also be a variablethat is used in the calculation.. Here is an example of how to add 2 numbers together and

store the result in a variable:

public class Variables

{

public static void main(String[] args)

{

int answer;

answer = 2 + 3;

}

}

Once you have stored a value in a variable you can use it in a calculation just like anumber.

public class Variables

{

public static void main(String[] args)

{

int answer;

int number = 2;

answer = number + 3;

}

}

Here is a table of operators which can be used in calculations:

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Remainder of division

Constants

Constants are variables with values that can't be changed. The value is assigned to aconstant when it is declared. Constants are used to give names to certain values so thattheir meaning is more obvious. The meaning of the number 3.14 is not obvious but if itwas given the name PI then you know immediatly what it means.Use the word final infront of a normal variable declaration to make it a constant.

public class Variables

{

public static void main(String[] args)

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 7/24

{

final double PI = 3.14;

}

}

Learn Java programming tutorial lesson3 - Decisions

What are decisions? 

A decision is a way of allowing a program to choose which code to run. If a condition ismet then one section of code will be run and if it is not then another section will be run.

The if decision structure

The if statement evaluates a condition and if the result is true then it runs the line of codethat follows it. Here is an example of how to test if the value of a variable called i is equalto 5:

public class Decisions

{

public static void main(String[] args)

{

int i = 5;

if (i == 5)

System.out.println("i is equal to 5");

}

}

If you change i to 4 and run this program again you will see that no message is printed.

Relational operators

You will see that a == has been used to test if the values are equal. It is important toknow that a = is for setting a value and a == is for testing a value. The == is called arelational operator. Here is a table of the other relational operators that can be used:

== Equal to

!= Not equal to> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 8/24

else

We know that if the condition is true then the code directly afer the if statement is run.You can run code for when the condition is false by using the else statement.

public class Decisions{

public static void main(String[] args)

{

int i = 4;

if (i == 5)

System.out.println("i is equal to 5");

else

System.out.println("i is not equal to 5");

}

}

Grouping statements

If you want to run more than 1 line of code in an if statement then you must group themtogether with curly brackets.

public class Decisions

{

public static void main(String[] args)

{

int i = 4;

if (i != 5)

{

System.out.println("i not is equal to 5");

System.out.println("i is equal to " + i);

}

}

}

Nested if structures

You can put if statements inside other if statments which will make them nested if statements. It is sometimes more efficient to use nested if statements such as in thefollowing example which finds out if a number is positive, negative or zero:

public class Decisions

{ public static void main(String[] args)

{

int i = 1;

if (i > 0)

System.out.println("Positive");

else

if (i < 0)

System.out.println("Negative");

else

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 9/24

System.out.println("Zero");

}

}

 AND, OR and NOT 

You can test if more than 1 condition is true using the AND(&&) operator. To test if only1 of many conditions is true use the OR(||) operator. The NOT(!) operator will change atrue to a false and a false to a true.

public class Decisions

{

public static void main(String[] args)

{

int i = 1;

int j = 1;

if (i == 1 && j == 1)

System.out.println("i is 1 and j is 1");

if (i == 1 || j == 2)System.out.println("Either i is 1 or j is 1");

if (!(i == 1))

System.out.println("i is not 1");

}

}

The switch decision structure

The switch structure is like having many if statements in one. It takes a variable and thenhas a list of actions to perform for each value that the variable could be. It also has anoptional part for when none of the values match. The break statement is used to break out

of the switch structure so that no more conditions are tested.

public class Decisions

{

public static void main(String[] args)

{

int i = 3;

switch(i)

{

case 1:

System.out.println("i is 1");

break;

case 2:

System.out.println("i is 2");break;

case 3:

System.out.println("i is 3");

break;

default:

System.out.println("Invalid value");

}

}

}

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 10/24

Learn Java programming tutorial lesson

4 - Loops

What is a loop? 

A loop is a way of repeating lines of code. If you want to for example print Hello on thescreen 10 times then you can either use System.out.println 10 times or you can put 1System.out.println in a loop that runs 10 times which takes a lot less lines of code.

For loop

The for loop goes from a number you give it to a second number you give it. It uses aloop counter variable to store the current loop number. Here is the format for a for loop:

for (set starting value; end condition; increment loop variable)

You first set the loop counter variable to the starting value. Next you set the endcondition. While the condition is true the loop will keep running but when it is false thenit will exit the loop. The last one is for setting the amount by which the loop variablemust be increased by each time it repeats the loop. Here is how you would do theexample of printing Hello 10 times using a for loop:

public class Loops

{

public static void main(String[] args)

{

int i;for (i = 1; i <=10; i++)

System.out.println("Hello");

}

}

Incrementing and decrementing 

i++ has been used to add 1 to i. This is called incrementing. You can decrement i byusing i--. If you use ++i then the value is incremented before the condition is tested and if it is i++ then i is incremented after the condition is tested.

Multiple lines of code in a loop

If you want to use more than 1 line of code in a loop then you must group them together  between curly brackets.

public class Loops

{

public static void main(String[] args)

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 11/24

{

int i;

for (i = 1; i <=10; i++)

{

System.out.println("Hello");

System.out.println(i);

}

}

}

While loop

The while loop will repeat itself while a certain condition is true. The condition is onlytested once every loop and not all the time while the loop is running. If you want to use aloop counter variable in a while loop then you must initialize it before you enter the loopand increment it inside the loop. Here is the Hello example using a while loop:

public class Loops

{public static void main(String[] args)

{

int i = 1;

while (i <= 10)

{

System.out.println("Hello");

i++;

}

}

}

Do while loop

The do while loop is like the while loop except that the condition is tested at the bottomof the loop instead of the top.

public class Loops

{

public static void main(String[] args)

{

int i = 1;

do

{

System.out.println("Hello");

i++;

}

while (i <= 10)

}

}

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 12/24

Learn Java programming tutorial lesson

5 - Data input and type conversions

Until now we have set the values of variables in the programs. Now we will learn how toget input from the user so that our programs are a bit more interesting and useful.

Reading single characters

To read a single character from the user you must use the System.in.read() method. Thiswill return and integer value of the key pressed which must be converted to a character.We use (char) in front of System.in.read() to convert the integer to a character. After theuser has pressed the key they must press enter and we must put a second System.in.read()to catch this second key press.

public class ReadChar{

public static void main(String[] args) throws Exception

{

char c;

System.out.println("Enter a character");

c = (char)System.in.read();

System.in.read();

System.out.println("You entered " + c);

}

}

You will see that it says "throws Exception" at the end of the main method declaration.

An exception is an error and "throws Exception" tells java to pass the error to theoperating system for handling. Your program will not compile if you don't put this in.

Reading strings

The easiest way to read a string is to use the graphical input dialog. We must import theJOptionPane.showInputDialog method before we can use it. Then we can use theJOptionPane.showInputDialog method to read the string. We can print the entered stringusing the JOptionPane.showMessageDialog method. You must then put a System.exit(0)at the end of the program or else the program will not stop running.

import javax.swing.*; 

public class ReadString

{

public static void main(String[] args)

{

String s;

s = JOptionPane.showInputDialog("Enter your name");

JOptionPane.showMessageDialog(null, "Your name is " + s);

System.exit(0);

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 13/24

}

}

Type conversions

Once you have read a string you might want to convert it to another data type such as aninteger. You have already seen in a previous example that you must use the type that youwant to convert to between brackets in front of the variable to be converted. Here is anexample of some conversions:

public class Convert

{

public static void main(String[] args)

{

int i;

char c = 'a';

i = (int)c;

i = 5;

c = (char)i;}

}

Strings are not variables but actually classes which is why we must use theInteger.parseInt() method to convert a string to an integer.

import javax.swing.*;

 

public class ConvertString

{

public static void main(String[] args)

{

String s;

int i;

s = JOptionPane.showInputDialog("Enter a number");

i = Integer.parseInt(s);

JOptionPane.showMessageDialog(null, "The number you entered is "

+ i);

System.exit(0);

}

}

Learn Java programming tutorial lesson

6 - Arrays

What is an array 

An array is group of variables that is given only one name. Each variable that makes upthe array is given a number instead of a name which makes it easier to work with usingloops among other things.

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 14/24

Declaring an array 

Declaring an array is the same as declaring a normal variable except that you must put aset of square brackets after the variable type. Here is an example of how to declare anarray of integers called a.

public class Array

{

public static void main(String[] args)

{

int[] a;

}

}

An array is more complex than a normal variable so we have to assign memory to thearray when we declare it. When you assign memory to an array you also set its size. Hereis an example of how to create an array that has 5 elements.

public class Array

{

public static void main(String[] args)

{

int[] a = new int[5];

}

}

Instead of assigning memory to the array you can assign values to it instead. This iscalled initializing the array because it is giving the array initial values.

public class Array

{public static void main(String[] args)

{

int[] a = {12, 23, 34, 45, 56};

}

}

Using an array 

You can access the values in an array using the number of the element you want to access between square brackets after the array's name. There is one important thing you mustremember about arrays which is they always start at 0 and not 1. Here is an example of 

how to set the values for an array of 5 elements.

public class Array

{

public static void main(String[] args)

{

int[] a = new int[5];

a[0] = 12;

a[1] = 23;

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 15/24

a[2] = 34;

a[3] = 45;

a[4] = 56;

}

}

A much more useful way of using an array is in a loop. Here is an example of how to usea loop to set all the values of an array to 0 which you will see is much easier than settingall the values to 0 seperately.

public class Array

{

public static void main(String[] args)

{

int[] a = new int[5];

for (int i = 0; i < 5; i++)

a[i] = 0;

}

}

Sorting an array 

Sometimes you will want to sort the elements of an array so that they go from the lowestvalue to the highest value or the other way around. To do this we must use the bubblesort. A bubble sort uses an outer loop to go from the last element of the array to the firstand an inner loop which goes from the first to the last. Each value is compared inside theinner loop against the value in front of it in the array and if it is greater than that valuethen it is swapped. Here is an example.

public class Array

{public static void main(String[] args)

{

int[] a = {3, 5, 1, 2, 4};

int i, j, temp;

for (i = 4; i >= 0; i--)

for (j = 0; j < i; j++)

if (a[j] > a[j + 1])

{

temp = a[j];

a[j] = a[j + 1];

a[j + 1] = temp;

}

}

}

2D arrays

So far we have been using 1-dimensional or 1D arrays. A 2D array can have values thatgo not only down but also across. Here are some pictures that will explain the difference between the 2 in a better way.

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 16/24

1D Array

0 1

1 2

2 3

3 44 5

2D Array

0 1 2

0 1 2 3

1 4 5 6

2 7 8 9

All that you need to do to create and use a 2D array is use 2 square brackets instead of 1.

public class Array

{

public static void main(String[] args)

{

int[][] a = new int[3][3];

a[0][0] = 1;

}

}

Learn Java programming tutorial lesson

7 - Object-Oriented

Programming(OOP)

What is Object-Oriented Programming? 

Object oriented programming or OOP is a way of writing programs using objects. Anobject is a data structure in memory that has attributes and methods. The attributes of anobject are the same as variables and the methods of an object are the same as functions or  procedures.

The reason for using objects instead of the old procedural method of programming is because objects group the variables and methods about something together instead of keeping them all apart as in procedural programming. There are many other reasons whyOOP is better which you will learn about later.

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 17/24

Using classes and objects

Before you can create an object you need to create a class. A class is the code for anobject and an object is the instance of a class in memory. When you create an object froma class it is called instantiating the object. To help you understand think of the plan for a

house. The plan for the house is like the class and the house that will be built from the plan is the object.

Creating a class

You have already been creating classes in the programs you have written so far. To showyou how they work we will need to create a separate class in a separate file. This classwill be called Student.

public class Student

{

}

 Now we will add 2 variables to the class which are the student's name and studentnumber.

public class Student

{

String studentName;

int studentNumber;

}

 Next we must add methods for getting and setting these variables.

public class Student

{

String studentName;

int studentNumber;

 

public void setStudentName(String s)

{

studentName = s;

}

 

public void setStudentNumber(int i)

{

studentNumber = i;

public String getStudentName()

{

return studentName;

}

 

public int getStudentNumber()

{

return studentNumber;

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 18/24

}

}

Instantiating an object 

 Now that we have finished writing the class we must create the main program that willinstantiate the object. We will call the main program class TestClass. It should look justlike how every other java program starts off.

public class TestClass

{

public static void main(String[] args)

{

}

}

 Now we will instantiate the object. To do this we declare a reference to the object calledstu and set it equal to a newly created object in memory.

public class TestClass

{

public static void main(String[] args)

{

Student stu = new Student();

}

}

Using the object 

 Now we can call the methods from the stu object to set the values of its variables. You

can't set the values of the variables in an object unless they are declared as public. Thismakes it safer to work with variables because they can't be changed by mistake byanother object.

public class TestClass

{

public static void main(String[] args)

{

Student stu = new Student();

stu.setStudentName("John Smith");

stu.setStudentNumber(12345);

System.out.println("Student Name: " + stu.getStudentName());

System.out.println("Student Number: " + stu.getStudentNumber());}

}

Constructors

A constructor is a method that is run when an object is instantiated. Constructors areuseful for initializing variables. The constructor is declared with only the name of the

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 19/24

class followed by brackets. Here is an example of the Student class that initializes bothstudent name and student number.

public class Student

{

String studentName;

int studentNumber; 

Student()

{

studentName = "No name";

studentNumber = 1;

}

 

public void setStudentName(String s)

{

studentName = s;

}

 

public void setStudentNumber(int i)

{

studentNumber = i;

}

 

public String getStudentName()

{

return studentName;

}

 

public int getStudentNumber()

{

return studentNumber;

}

}

You can also pass parameters to a constructor when you instantiate an object. All youneed to do is add the parameters in the brackets after the constructor declaration just likea normal method.

public class Student

{

String studentName;

int studentNumber;

 

Student(String s, int i)

{studentName = s;

studentNumber = i;

}

 

public void setStudentName(String s)

{

studentName = s;

}

 

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 20/24

public void setStudentNumber(int i)

{

studentNumber = i;

}

 

public String getStudentName()

{

return studentName;

}

 

public int getStudentNumber()

{

return studentNumber;

}

}

 Now all you need to do is put the parameters in the brackets when you instantiate theobject in the main program.

 public class TestClass{

public static void main(String[] args){

Student stu = new Student("John Smith",12345);System.out.println("Student Name: " + stu.getStudentName());System.out.println("Student Number: " + stu.getStudentNumber());

}}

Learn Java programming tutorial lesson

8 - Inheritance

What is inheritance? 

Inheritance is the ability of objects in java to inherit properties and methods from other objects. When an object inherits from another object it can add its own properties andmethods. The object that is being inherited from is called the parent or base class and the

class that is inheriting from the parent is called the child or derived class.

How to use inheritance

We will first create a parent class called Person. We will then create a child class calledStudent. Then we will create a program to use the Student class. The following is a

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 21/24

Person class which has a variable for the person's name. There are also set and getmethods for the name.

class Person

{

private String name;

 public void setName(String n)

{

name = n;

}

 

public String getName()

{

return name;

}

}

 Now we will create the Student class that has a variable for the student number and the

get and set methods for student number. The extends keyword is used to inherit from thePerson class in the following example.

class Student extends Person

{

private String stuNum;

 

public void setStuNum(String sn)

{

stuNum = sn;

}

 

public String getStuNum()

{return stuNum;

}

}

Finally we have to create a program that will instantiate a Student object, set the nameand student number and then print the values using the get methods.

public class TestInheritance

{

public static void main(String[] args)

{

Student stu = new Student();stu.setName("John Smith");

stu.setStuNum("12345");

System.out.println("Student Name: " + stu.getName());

System.out.println("Student Number: " + stu.getStuNum());

}

}

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 22/24

 Abstract inheritance

Abstract classes are created only for the purpose of being inherited from. In fact you can'tinstantiate an object from an abstract class. You must put the abstract keyword in front of the class name declaration to create an abstract class. We can change the Person class

above to show how it works.

abstract class Person

{

private String name;

 

public void setName(String n)

{

name = n;

}

 

public String getName()

{

return name;}

}

Interfaces

Interfaces are like abstract classes because you can't instantiate them and they are onlyused for being inherited from. The difference is that interfaces are not allowed to havevariables unless they are constants and methods are not allowed to have a body. The pointof an interface is for you to override the methods that are declared in it. You must use theimplements keyword instead of extends when using interfaces. Here is an example of thePerson class as an interface and the Student class that uses the Person interface.

interface Person

{

public void setName(String n);

public String getName();

}

 

class Student implements Person

{

private String stuNum;

private String name;

 

public void setStuNum(String sn)

{stuNum = sn;

}

 

public String getStuNum()

{

return stuNum;

}

 

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 23/24

public void setName(String n)

{

name = n;

}

 

public String getName()

{

return name;

}

}

How to Learn Programming

The 3 steps to learn programming are:

1. Decide why you want to learn2. Choose a programming language

3. Decide how you are going to learn

Decide why you want to learn

You first need to decide whether you are serious about learning programming and want a job in programming or if you just want to program for a hobby. This will help you choosea programming language and choose the way you are going to learn.

Choose a programming language

Once you have a reason for learning programming you can choose a programming

language. If you are serious about programming then you should start off with a languagelike C because it is a popular language for both learning and business use and there aremany C tutorials, books and resources available. C is difficult to learn but you will get the benefits of learning it later on. You should focus on just one language while learning the basics of programming. It is better to know 1 language very well than to know a littleabout many. If you have an in depth knowledge of just 1 language then it is much easier to learn other languages.

Alternatives to C:

• C# - A new and popular language that is based on C but has a lot more features

and is much easier to use• Pascal - A very popular learning language that is easier to use than C• C++ - Based on C but includes advanced features. It is better to learn C before C+

+• Java - Java is becoming a popular business and learning language. Doesn't teach

you some important concepts that C/C++ does

8/3/2019 Learn Java Programming

http://slidepdf.com/reader/full/learn-java-programming 24/24

If you are learning programming as a hobby then you should choose a programminglanguage like Visual Basic because it is easy to use and you can start making useful programs straight away.

Alternatives to Visual Basic:

• Delphi - Delphi is a little bit more difficult than Visual Basic but teaches other important programming concepts

• Scripting Languages(Python, Perl) - Easier to program in than compiledlanguages but not always as useful

Decide how you are going to learn

People who are serious about programming should think about taking a course at acollege or university. You will find it easier to put the effort into learning when you haveto pay for it. They also teach you everything you need to know so that you don't miss out

on anything.

If you are programming for fun then you should get yourself a book or find some tutorialson the Internet.

Comments

You will find that programming is difficult at first but becomes easier later. You shouldtry not to quit if you think it is too difficult for you because most programmers oncethought it was difficult but have no problems today. Learning how to program is veryrewarding and is worth all the hard work. Good Luck!