Java Basics Continued
Java Basics Continued
In the previous chapter, we used the term "variable" for x in the example (as
shown below). It is actually an attribute of the class. Or you could say that
class attributes are variables within a class:
Example
Create a class called "Main" with two attributes: x and y:
int x = 5;
int y = 3;
Accessing Attributes
You can access attributes by creating an object of the class, and by using the
dot syntax (.):
The following example will create an object of the Main class, with the
name myObj. We use the x attribute on the object to print its value:
Example
Create an object called "myObj" and print the value of x:
int x = 5;
System.out.println(myObj.x);
}
Modify Attributes
You can also modify attribute values:
Example
Set the value of x to 40:
int x;
myObj.x = 40;
System.out.println(myObj.x);
Example
Change the value of x to 25:
int x = 10;
System.out.println(myObj.x);
}
If you don't want the ability to override existing values, declare the attribute
as final:
Example
public class Main {
System.out.println(myObj.x);
The final keyword is useful when you want a variable to always store the same
value, like PI (3.14159...).
The final keyword is called a "modifier". You will learn more about these in
the Java access modifiers.
Multiple Objects
If you create multiple objects of one class, you can change the attribute values
in one object, without affecting the attribute values in the other:
Example
Multiple Attributes
You can specify as many attributes as you want:
Example
public class Main {
String fname = "John";
String lname = "Doe";
int age = 24;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Age: " + myObj.age);
}
}
Java Class Methods
You learned from the Java Methods chapter that methods are declared within a
class, and that they are used to perform certain actions:
Example
Create a method named myMethod() in Main:
System.out.println("Hello World!");
myMethod() prints a text (the action), when it is called. To call a method, write
the method's name followed by two parentheses () and a semicolon;
Example
Inside main, call myMethod():
System.out.println("Hello World!");
myMethod();
Non-Static Method
Any method of a class which is not static is called non-static method or an instance
method.
Following are some of the important differences between static and non-static method.
Tiger.roar();
tiger.eat();
class Tiger {
System.out.println("Tiger eats");
System.out.println("Tiger roars");
Output
Tiger roars
Tiger eats
Access Methods With an Object
Example
Create a Car object named myCar. Call
the fullThrottle() and speed() methods on the myCar object, and run the
program:
3) The fullThrottle() method and the speed() method will print out some
text, when they are called.
4) The speed() method accepts an int parameter called maxSpeed - we will use
this in 8).
5) In order to use the Main class and its methods, we need to create
an object of the Main Class.
6) Then, go to the main() method, which you know by now is a built-in Java
method that runs your program (any code inside main is executed).
7) By using the new keyword we created an object with the name myCar.
8) Then, we call the fullThrottle() and speed() methods on the myCar object,
and run the program using the name of the object (myCar), followed by a dot
(.), followed by the name of the method (fullThrottle(); and speed(200);).
Notice that we add an int parameter of 200 inside the speed() method.
Remember that..
The dot (.) is used to access the object's attributes and methods.
Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory:
Main.java
Second.java
Main.java
Second.java
class Second {
Example
Create a constructor:
// Outputs 5
Note that the constructor name must match the class name, and it cannot
have a return type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial
values for object attributes.
Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.
The following example adds an int y parameter to the constructor. Inside the
constructor we set x to y (x=y). When we call the constructor, we pass a
parameter to the constructor (5), which will set the value of x to 5:
Example
public class Main {
int x;
public Main(int y) {
x = y;
System.out.println(myObj.x);
// Outputs 5
int modelYear;
String modelName;
modelYear = year;
modelName = name;
The public keyword is an access modifier, meaning that it is used to set the
access level for classes, attributes, methods and constructors.
Access Modifiers
For classes, you can use either public or default:
Modifier Description
For attributes, methods and constructors, you can use the one of the
following:
Modifier Description
default The code is only accessible in the same package. This is used when you don't
specify a modifier.
Non-Access Modifiers
For classes, you can use either final or abstract:
Modifier Description
final The class cannot be inherited by other classes (You will learn more about inheritance
below.)
abstract The class cannot be used to create objects (To access an abstract class, it must be
inherited from another class.)
For attributes and methods, you can use the one of the following:
Modifier Description
static Attributes and methods belongs to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on methods. The
method does not have a body, for example abstract void run();. The body is
provided by the subclass (inherited from). You will learn more about inheritance
and abstraction in the Inheritance and Abstraction below.
Final
If you don't want the ability to override existing attribute values, declare
attributes as final:
Example
public class Main {
System.out.println(myObj.x);
}
Static
A static method means that it can be accessed without creating an object of the
class, unlike public:
Example
An example to demonstrate the differences between static and public methods:
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating
objects");
}
// Main method
public static void main(String[ ] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would output an error
Example
// Code from filename: Main.java
// abstract class
abstract class Main {
public String fname = "John";
public int age = 24;
public abstract void study(); // abstract method
}
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in
the Java Development Environment.
The library is divided into packages and classes. Meaning you can either
import a single class (along with its methods and attributes), or a whole
package that contain all the classes that belong to the specified package.
Syntax
import package.name.Class; // Import a single class
Example
import java.util.Scanner;
To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation. In our example,
we will use the nextLine() method, which is used to read a complete line:
Example
Using the Scanner class to get user input:
import java.util.Scanner;
class MyClass {
System.out.println("Enter username");
}
Import a Package
There are many packages to choose from. In the previous example, we used
the Scanner class from the java.util package. This package also contains date
and time facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The
following example will import ALL the classes in the java.util package:
Example
import java.util.*;
In the example below, the Car class (subclass) inherits the attributes and
methods from the Vehicle class (superclass):
Example
class Vehicle {
System.out.println("Tuut, tuut!");
}
class Car extends Vehicle {
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class)
and the value of the modelName from the Car class
...
...
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract method: can only be used in an abstract class, and it does not
have a body. The body is provided by the subclass (inherited from).
From the example above, it is not possible to create an object of the Animal
class:
Remember from Inheritance that we use the extends keyword to inherit from a
class.
Example
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Note: Abstraction can also be achieved with Interfaces, which you will learn
more about next.
Interfaces
Another way to achieve abstraction in Java, is with interfaces.
Example
// interface
interface Animal {
Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Notes on Interfaces:
2) Java does not support "multiple inheritance" (a class can only inherit from
one superclass). However, it can be achieved with interfaces, because the class
can implement multiple interfaces. Note: To implement multiple interfaces,
separate them with a comma (see example below).
Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
Example
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
Java Exceptions
When executing Java code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message.
The technical term for this is: Java will throw an exception (throw an error).
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
System.out.println(myNumbers[10]); // error!
}
The output will be something like this:
If an error occurs, we can use try...catch to catch the error and execute some
code to handle it:
Example
public class Main {
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
Example
public class Main {
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
} finally {
The throw statement is used together with an exception type. There are many
exception types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException , Secu
rityException, etc:
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or
older, print "Access granted":
Example
checkAge(20);
The output will be:
Access granted - You are old enough!
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at
the same time.
Creating a Thread
There are two ways to create a thread.
It can be created by extending the Thread class and overriding its run() method:
Extend Syntax
public class Main extends Thread {
Implement Syntax
public class Main implements Runnable {
}
Running Threads
If the class extends the Thread class, the thread can be run by creating an
instance of the class and call its start() method:
Extend Example
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
If the class implements the Runnable interface, the thread can be run by passing
an instance of the class to a Thread object's constructor and then calling the
thread's start() method:
Implement Example
public class Main implements Runnable {
public static void main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
Differences between "extending" and "implementing" Threads
The major difference is that when a class extends the Thread class, you cannot
extend any other class, but by implementing the Runnable interface, it is
possible to extend from another class as well, like: class MyClass extends
OtherClass implements Runnable.
To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation. In our example, we
will use the nextLine() method, which is used to read Strings:
Example
import java.util.Scanner; // Import the Scanner class
class Main {
System.out.println("Enter username");
}
Input Types
In the example above, we used the nextLine() method, which is used to read
Strings. To read other types, look at the table below:
Method Description
In the example below, we use different methods to read data of various types:
Example
import java.util.Scanner;
class Main {
// String input
// Numerical input
Note: If you enter wrong input (e.g. text in a numerical input), you will get an
exception/error message (like "InputMismatchException").