0% found this document useful (0 votes)
2 views50 pages

Oop Using Java

Uploaded by

shahidraza36202
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views50 pages

Oop Using Java

Uploaded by

shahidraza36202
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Java - What is OOP?

OOP stands for Object-Oriented Programming.


Procedural programming is about writing procedures or methods that perform operations on the data, while
object-oriented programming is about creating objects that contain both data and methods.
Object-oriented programming has several advantages over procedural programming:
 OOP is faster and easier to execute
 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to maintain,
modify and debug
 OOP makes it possible to create full reusable applications with less code and shorter development time
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract
out the codes that are common for the application, and place them at a single place and reuse them instead of
repeating it.

Java Install
if you want to run Java on your own computer, follow the instructions below.
Some PCs might have Java already installed.
To check if you have Java installed on a Windows PC, search in the start bar for Java or type the following in
Command Prompt (cmd.exe):
C:\Users\Your Name>java -version
If Java is installed, you will see something like this (depending on version):
java version "22.0.0" 2024-08-21 LTS
Java(TM) SE Runtime Environment 22.9 (build 22.0.0+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 22.9 (build 22.0.0+13-LTS, mixed mode)
If you do not have Java installed on your computer, you can download it at oracle.com.
Note: In this tutorial, we will write Java code in a text editor. However, it is possible to write Java in an
Integrated Development Environment, such as IntelliJ IDEA, Netbeans or Eclipse, which are particularly useful
when managing larger collections of Java files.

Java Quickstart
In Java, every application begins with a class name, and that class must match the filename.
Let's create our first Java file, called Main.java, which can be done in any text editor (like Notepad).
The file should contain a "Hello World" message, which is written with the following code:
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus
on how to run the code above.
Save the code in Notepad as "Main.java". Open Command Prompt (cmd.exe), navigate to the directory where
you saved your file, and type "javac Main.java":
C:\Users\Your Name>javac Main.java
This will compile your code. If there are no errors in the code, the command prompt will take you to the next
line. Now, type "java Main" to run the file:
C:\Users\Your Name>java Main
The output should read:
Hello World
Congratulations! You have written and executed your first Java program.

Java Syntax
In the previous chapter, we created a Java file called Main.java, and we used the following code to print "Hello
World" to the screen:
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}

Example explained
Every line of code that runs in Java must be inside a class. And the class name should always start with an
uppercase first letter. In our example, we named the class Main.
Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.
The name of the java file must match the class name. When saving the file, save it using the class name and add
".java" to the end of the filename. To run the example above on your computer, make sure that Java is properly
installed: Go to the Get Started Chapter for how to install Java. The output should be:
Hello World

The main Method


The main() method is required and you will see it in every Java program:
public static void main(String[] args)
Any code inside the main() method will be executed. Don't worry about the keywords before and after it. You will
get to know them bit by bit while reading this tutorial.
For now, just remember that every Java program has a class name which must match the filename, and that every
program must contain the main() method.

System.out.println()
Inside the main() method, we can use the println() method to print a line of text to the screen:
public static void main(String[] args) {
System.out.println("Hello World");
}
Note: The curly braces {} marks the beginning and the end of a block of code.
System is a built-in Java class that contains useful members, such as out, which is short for "output".
The println() method, short for "print line", is used to print a value to the screen (or a file).
Don't worry too much about how System, out and println() works. Just know that you need them together to print
stuff to the screen.
You should also note that each code statement must end with a semicolon (;).

Java Output / Print

Print Text
You learned from the previous chapter that you can use the println() method to output values or print text in Java:

Example
System.out.println("Hello World!");
You can add as many println() methods as you want. Note that it will add a new line for each method:

Example
System.out.println("Hello World!");
System.out.println("I am learning Java.");
System.out.println("It is awesome!");

Double Quotes
Text must be wrapped inside double quotations marks "".
If you forget the double quotes, an error occurs:
Example
System.out.println("This sentence will work!");
System.out.println(This sentence will produce an error);

The Print() Method


There is also a print() method, which is similar to println().
The only difference is that it does not insert a new line at the end of the output:

Example
System.out.print("Hello World! ");
System.out.print("I will print on the same line.");
Note that we add an extra space (after "Hello World!" in the example above) for better readability.
In this tutorial, we will only use println() as it makes the code output easier to read.

Java - What are Classes and Objects?


Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and objects:

class
Fruit

objects
Apple
Banana
Mango
Another example:

class
Car

objects
Volvo
Audi
Toyota
So, a class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the variables and methods from the class

Java Classes/Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in
real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and
brake.
A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class
To create a class, use the keyword class:
Create a class named "Main" with a variable x:
public class Main {
int x = 5;
}

Create an Object
In Java, an object is created from a class. We have already created the class named Main, so now we can use this
to create objects.
To create an object of Main, specify the class name, followed by the object name, and use the keyword new:

Example
Create an object called "myObj" and print the value of x:
public class Main {
int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
}
}

Multiple Objects
You can create multiple objects of one class:

Example
Create two objects of Main:
public class Main {
int x = 5;

public static void main(String[] args) {


Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}

Using Multiple Classes


You can also create an object of a class and access it in another class. This is often used for better organization of
classes (one class has all the attributes and methods, while the other class holds the main() method (code to be
executed)).
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/folder:
 Main.java
 Second.java

Main.java
public class Main {
int x = 5;
}

Second.java
class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
When both files have been compiled:
C:\Users\Your Name>javac Main.java
C:\Users\Your Name>javac Second.java
Run the Second.java file:
C:\Users\Your Name>java Second
And the output will be:
5
Java Class Attributes
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:
public class Main {
int x = 5;
int y = 3;
}
Another term for class attributes is fields.

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:
public class Main {
int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
}
}

Modify Attributes
You can also modify attribute values:

Example
Set the value of x to 40:
public class Main {
int x;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 40;
System.out.println(myObj.x);
}
}

Or override existing values:

Example
Change the value of x to 25:
public class Main {
int x = 10;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 25; // x is now 25
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 {
final int x = 10;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}

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
Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:
public class Main {
int x = 5;

public static void main(String[] args) {


Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
myObj2.x = 25;
System.out.println(myObj1.x); // Outputs 5
System.out.println(myObj2.x); // Outputs 25
}
}

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:
public class Main {
static void myMethod() {
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():
public class Main {
static void myMethod() {
System.out.println("Hello World!");
}

public static void main(String[] args) {


myMethod();
}
}

// Outputs "Hello World!"

Static vs. Public


You will often see Java programs that have either static or public attributes and methods.
In the example above, we created a static method, which means that it can be accessed without creating an object
of the class, unlike public, which can only be accessed by objects:

Example
An example to demonstrate the differences between static and public methods:
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// 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 compile an error

Main myObj = new Main(); // Create an object of Main


myObj.myPublicMethod(); // Call the public method on the object
}
}

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:
// Create a Main class
public class Main {

// Create a fullThrottle() method


public void fullThrottle() {
System.out.println("The car is going as fast as it can!");
}

// Create a speed() method and add a parameter


public void speed(int maxSpeed) {
System.out.println("Max speed is: " + maxSpeed);
}

// Inside main, call the methods on the myCar object


public static void main(String[] args) {
Main myCar = new Main(); // Create a myCar object
myCar.fullThrottle(); // Call the fullThrottle() method
myCar.speed(200); // Call the speed() method
}
}

// The car is going as fast as it can!


// Max speed is: 200

Example explained
1) We created a custom Main class with the class keyword.
2) We created the fullThrottle() and speed() methods in the Main class.
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.
To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon (;).
A class must have a matching filename (Main and Main.java).

Using Multiple Classes


Like we specified in the Classes chapter, it is a good practice to create an object of a class and access it in another
class.
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
public class Main {
public void fullThrottle() {
System.out.println("The car is going as fast as it can!");
}

public void speed(int maxSpeed) {


System.out.println("Max speed is: " + maxSpeed);
}
}

Second.java
class Second {
public static void main(String[] args) {
Main myCar = new Main(); // Create a myCar object
myCar.fullThrottle(); // Call the fullThrottle() method
myCar.speed(200); // Call the speed() method
}
}
When both files have been compiled:
C:\Users\Your Name>javac Main.java
C:\Users\Your Name>javac Second.java
Run the Second.java file:
C:\Users\Your Name>java Second
And the output will be:
The car is going as fast as it can!
Max speed is: 200

Java Constructors

Java Constructors
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created.
It can be used to set initial values for object attributes:

Example
Create a constructor:
// Create a Main class
public class Main {
int x; // Create a class attribute
// Create a class constructor for the Main class
public Main() {
x = 5; // Set the initial value for the class attribute x
}

public static void main(String[] args) {


Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}

// 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;
}

public static void main(String[] args) {


Main myObj = new Main(5);
System.out.println(myObj.x);
}
}
// Outputs 5

You can have as many parameters as you want:

Example
public class Main {
int modelYear;
String modelName;

public Main(int year, String name) {


modelYear = year;
modelName = name;
}

public static void main(String[] args) {


Main myCar = new Main(1969, "Mustang");
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
}

// Outputs 1969 Mustang

Java this Keyword


The this keyword in Java refers to the current object in a method or constructor.
The this keyword is often used to avoid confusion when class attributes have the same name as method or
constructor parameters.

Accessing Class Attributes


Sometimes a constructor or method has a parameter with the same name as a class variable. When this happens,
the parameter temporarily hides the class variable inside that method or constructor.
To refer to the class variable and not the parameter, you can use the this keyword:

Example
public class Main {
int x; // Class variable x

// Constructor with one parameter x


public Main(int x) {
this.x = x; // refers to the class variable x
}

public static void main(String[] args) {


// Create an object of Main and pass the value 5 to the constructor
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}
Output:
Value of x = 5
Tip: Think of this.x = x; as: "this.x (the class variable) gets the value of x (the parameter)."
Without this, the code above x = x; would set the parameter x equal to itself, and the class variable would stay
uninitialized (0).

Calling a Constructor from Another Constructor


You can also use this() to call another constructor in the same class.
This is useful when you want to provide default values or reuse initialization code instead of repeating it.

Example
public class Main {
int modelYear;
String modelName;

// Constructor with one parameter


public Main(String modelName) {
// Call the two-parameter constructor to reuse code and set a default year
this(2020, modelName);
}

// Constructor with two parameters


public Main(int modelYear, String modelName) {
// Use 'this' to assign values to the class variables
this.modelYear = modelYear;
this.modelName = modelName;
}

// Method to print car information


public void printInfo() {
System.out.println(modelYear + " " + modelName);
}

public static void main(String[] args) {


// Create a car with only model name (uses default year)
Main car1 = new Main("Corvette");

// Create a car with both model year and name


Main car2 = new Main(1969, "Mustang");

car1.printInfo();
car2.printInfo();
}
}
Output:
2020 Corvette
1969 Mustang
Note: The call to this() must be the first statement inside the constructor.

When to use this?


 When a constructor or method has a parameter with the same name as a class variable, use this to update
the class variable correctly.
 To call another constructor in the same class and reuse code.

Modifiers
By now, you are quite familiar with the public keyword that appears in almost all of our examples:
public class Main
The public keyword is an access modifier, meaning that it is used to set the access level for classes, attributes,
methods and constructors.
We divide modifiers into two groups:
 Access Modifiers - controls the access level
 Non-Access Modifiers - do not control access level, but provides other functionality

Access Modifiers
For classes, you can use either public or default:
Modifier Description

public The class is accessible by any other class

default The class is only accessible by classes in the same package. This is used when you don't specify a
modifier. You will learn more about packages in the Packages chapter

For attributes, methods and constructors, you can use the one of the following:

Modifier Description

public The code is accessible for all classes

private The code is only accessible within the declared class

default The code is only accessible in the same package. This is used when you don't specify a modifier.
You will learn more about packages in the Packages chapter

protected The code is accessible in the same package and subclasses. You will learn more about subclasses
and superclasses in the Inheritance chapter

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 in
the Inheritance chapter)

abstract The class cannot be used to create objects (To access an abstract class, it must be inherited from
another class. You will learn more about inheritance and abstraction in
the Inheritance and Abstraction chapters)

For attributes and methods, you can use the one of the following:

Modifier Description

final Attributes and methods cannot be overridden/modified

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 chapters

transient Attributes and methods are skipped when serializing the object containing them

synchronized Methods can only be accessed by one thread at a time

volatile The value of an attribute is not cached thread-locally, and is always read from the "main memory"

Final
If you don't want the ability to override existing attribute values, declare attributes as final:

Example
public class Main {
final int x = 10;
final double PI = 3.14;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 50; // will generate an error: cannot assign a value to a final variable
myObj.PI = 25; // will generate an error: cannot assign a value to a final variable
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 class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}

// 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

Main myObj = new Main(); // Create an object of Main


myObj.myPublicMethod(); // Call the public method
}
}

Abstract
An abstract method belongs to an abstract class, and it does not have a body. The body is provided by the subclass:

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
}

// Subclass (inherit from Main)


class Student extends Main {
public int graduationYear = 2018;
public void study() { // the body of the abstract method is provided here
System.out.println("Studying all day long");
}
}
// End code from filename: Main.java

// Code from filename: Second.java


class Second {
public static void main(String[] args) {
// create an object of the Student class (which inherits attributes and methods from Main)
Student myObj = new Student();

System.out.println("Name: " + myObj.fname);


System.out.println("Age: " + myObj.age);
System.out.println("Graduation Year: " + myObj.graduationYear);
myObj.study(); // call abstract method
}
}

Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you
must:
 declare class variables/attributes as private
 provide public get and set methods to access and update the value of a private variable

Get and Set


You learned from the previous chapter that private variables can only be accessed within the same class (an
outside class has no access to it). However, it is possible to access them if we provide public get and set methods.
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter
in upper case:

Example
public class Person {
private String name; // private = restricted access

// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}

Example explained
The get method returns the value of the variable name.
The set method takes a parameter (newName) and assigns it to the name variable. The this keyword is used to
refer to the current object.
However, as the name variable is declared as private, we cannot access it from outside this class:

Example
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.name = "John"; // error
System.out.println(myObj.name); // error
}
}
If the variable was declared as public, we would expect the following output:
John
However, as we try to access a private variable, we get an error:
MyClass.java:4: error: name has private access in Person
myObj.name = "John";
^
MyClass.java:5: error: name has private access in Person
System.out.println(myObj.name);
^
2 errors
Instead, we use the getName() and setName() methods to access and update the variable:

Example
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName());
}
}

// Outputs "John"

Why Encapsulation?
 Better control of class attributes and methods
 Class attributes can be made read-only (if you only use the get method), or write-only (if you only use
the set method)
 Flexible: the programmer can change one part of the code without affecting other parts
 Increased security of data

Java Inheritance (Subclass and Superclass)


In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance
concept" into two categories:
 subclass (child) - the class that inherits from another class
 superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword.
In the example below, the Car class (subclass) inherits the attributes and methods from the Vehicle class
(superclass):

Example
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}

class Car extends Vehicle {


private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {

// Create a myCar object


Car myCar = new Car();
// 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
System.out.println(myCar.brand + " " + myCar.modelName);
}
}

Did you notice the protected modifier in Vehicle?


We set the brand attribute in Vehicle to a protected access modifier. If it was set to private, the Car class would
not be able to access it.

Why And When To Use "Inheritance"?


- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.
Tip: Also take a look at the next chapter, Polymorphism, which uses inherited methods to perform different
tasks.

The final Keyword


If you don't want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:
final class Vehicle {
...
}

class Car extends Vehicle {


...
}
The output will be something like this:
Main.java:9: error: cannot inherit from final Vehicle
class Main extends Vehicle {
^
1 error)

Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by
inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another
class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in
different ways.
For example, think of a superclass called Animal that has a method called animalSound(). Subclasses of
Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the
pig oinks, and the cat meows, etc.):

Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}

class Pig extends Animal {


public void animalSound() {
System.out.println("The pig says: wee wee");
}
}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.
Now we can create Pig and Dog objects and call the animalSound() method on both of them:

Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}

class Pig extends Animal {


public void animalSound() {
System.out.println("The pig says: wee wee");
}
}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow wow");
}
}

class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}

Why And When To Use "Inheritance" and "Polymorphism"?


- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.

Abstract Classes and Methods


Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the
next chapter).
The abstract keyword is a non-access modifier, used for classes and methods:
 Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited
from another class).

 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).
An abstract class can have both abstract and regular methods:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}

From the example above, it is not possible to create an object of the Animal class:
Animal myObj = new Animal(); // will generate an error
To access the abstract class, it must be inherited from another class. Let's convert the Animal class we used in
the Polymorphism chapter to an abstract class:
Remember from the Inheritance chapter 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");
}
}

// Subclass (inherit from Animal)


class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Why And When To Use Abstract Classes and Methods?
To achieve security - hide certain details and only show the important details of an object.
Note: Abstraction can also be achieved with Interfaces,

Java Methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.

Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by parentheses ().
Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to
perform certain actions:

Example
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}

Example Explained
 myMethod() is the name of the method
 static means that the method belongs to the Main class and not an object of the Main class. You will
learn more about objects and how to access methods through objects later in this tutorial.
 void means that this method does not have a return value. You will learn more about return values later
in this chapter

Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
}
}

// Outputs "I just got executed!"

A method can also be called multiple times:

Example
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
myMethod();
myMethod();
}
}

// I just got executed!


// I just got executed!
// I just got executed!

Java Method Parameters


Parameters and Arguments
Information can be passed to methods as a parameter. Parameters act as variables inside the method.
Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you
want, just separate them with a comma.
The following example has a method that takes a String called fname as parameter. When the method is called,
we pass along a first name, which is used inside the method to print the full name:

Example
public class Main {
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}

public static void main(String[] args) {


myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

When a parameter is passed to the method, it is called an argument. So, from the example above: fname is
a parameter, while Liam, Jenny and Anja are arguments.

Multiple Parameters
You can have as many parameters as you like:

Example
public class Main {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}

// Liam is 5
// Jenny is 8
// Anja is 31

Note that when you are working with multiple parameters, the method call must have the same number of
arguments as there are parameters, and the arguments must be passed in the same order.

A Method with If...Else


It is common to use if...else statements inside methods:

Example
public class Main {

// Create a checkAge() method with an integer variable called age


static void checkAge(int age) {

// If age is less than 18, print "access denied"


if (age < 18) {
System.out.println("Access denied - You are not old enough!");

// If age is greater than, or equal to, 18, print "access granted"


} else {
System.out.println("Access granted - You are old enough!");
}

public static void main(String[] args) {


checkAge(20); // Call the checkAge method and pass along an age of 20
}
}

// Outputs "Access granted - You are old enough!"

Java Method Overloading

Method Overloading
With method overloading, multiple methods can have the same name with different parameters:

Example
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
Consider the following example, which has two methods that add numbers of different type:

Example
static int plusMethodInt(int x, int y) {
return x + y;
}

static double plusMethodDouble(double x, double y) {


return x + y;
}

public static void main(String[] args) {


int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
Instead of defining two methods that should do the same thing, it is better to overload one.
In the example below, we overload the plusMethod method to work for both int and double:

Example
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}

public static void main(String[] args) {


int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}

Note: Multiple methods can have the same name as long as the number and/or type of parameters are different.

Interfaces
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with empty bodies:

Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with
the implements keyword (instead of extends). The body of the interface method is provided by the "implement"
class:

Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}

Notes on Interfaces:
 Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible
to create an "Animal" object in the MyMainClass)
 Interface methods do not have a body - the body is provided by the "implement" class
 On implementation of an interface, you must override all of its methods
 Interface methods are by default abstract and public
 Interface attributes are by default public, static and final
 An interface cannot contain a constructor (as it cannot be used to create objects)

Why And When To Use Interfaces?


1) To achieve security - hide certain details and only show the important details of an object (interface).
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 DemoClass implements FirstInterface, SecondInterface {


public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}

class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}

Java Errors
Even experienced Java developers make mistakes. The key is learning how to spot and fix them!
These pages cover common errors and helpful debugging tips to help you understand what's going wrong and
how to fix it.

Types of Errors in Java


Error Type Description
Compile-Time Error Detected by the compiler. Prevents code from running.

Runtime Error Occurs while the program is running. Often causes crashes.

Logical Error Code runs but gives incorrect results. Hardest to find.

Common Compile-Time Errors


Compile-time errors occur when the program cannot compile due to syntax or type issues.
Here are some examples:
1) Missing Semicolon

Example
int x = 5
System.out.println(x);
Result:
error: ';' expected
Tip: Java requires a semicolon at the end of every statement (int x = 5;).
2) Undeclared Variables

Example
System.out.println(myVar);
Result:
cannot find symbol
symbol: variable myVar
Tip: You must declare a variable before using it (int myVar = 50;).
3) Mismatched Types

Example
int x = "Hello";
Result:
incompatible types: String cannot be converted to int
Tip: Make sure the value matches the variable type (String x = "Hello";).

Common Runtime Errors


Runtime errors occur when the program compiles but crashes or behaves unexpectedly.
Here are some examples:
1) Division by Zero
Example
int x = 10;
int y = 0;
int result = x / y;
System.out.println(result);
Result:
Exception in thread "main" java.lang.ArithmeticException: / by zero
2) Array Index Out of Bounds

Example
int[] numbers = {1, 2, 3};
System.out.println(numbers[8]);
Result:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 3

Logical Errors
Logical errors happen when the code runs, but the result is not what you thought:

Example:
int x = 10;
int y = 2;
int sum = x - y;
System.out.println("x + y = " + sum);
Result:
x+y=8
Expected Result: 12
Logical Error: The code mistakenly subtracts instead of adds.
Tip: Test your program with different inputs to catch logic flaws (try using x + y instead). This is part
of debugging, which you will learn more about in the next chapter.

Good Habits to Avoid Errors


 Use meaningful variable names
 Read the error message carefully. What line does it mention?
 Check for missing semicolons or braces
 Look for typos in variable or method names

Java Debugging
After learning about common errors, the next step is understanding how to debug your Java code - that is, how to
find and fix those errors effectively.
This page introduces simple debugging techniques that are useful for beginners and helpful even for experienced
developers.

What is Debugging?
Debugging is the process of identifying and fixing errors or bugs in your code.
It often involves:
 Reading error messages
 Tracing variable values step by step
 Testing small pieces of code independently
Tip: Debugging is a skill that improves with practice. The more you debug, the better you get at spotting
problems quickly.

Print Statements for Debugging


The most basic (and often most effective) way to debug Java code is to use System.out.println() to print values
and check the flow of the program.
In this example, the first line "Before division" will print, but the second line is never reached because the
program crashes due to division by zero:

Example
int x = 10;
int y = 0;

System.out.println("Before division"); // Debug output

int result = x / y; // Crashes

System.out.println("Result: " + result); // Never runs


Result:
Before division
Exception in thread "main" java.lang.ArithmeticException: / by zero
Tip: Add print statements before and after key lines of code to find out where things go wrong.

Check Variable Values


If something unexpected happens, print out the values of your variables:
Example
int age = 17;
System.out.println("Age: " + age);

if (age >= 18) {


System.out.println("Access granted");
} else {
System.out.println("Access denied");
}
Tip: This is a good way to test whether a condition is working correctly - try changing age to 18 or 19 and
observe the output!

Debugging with IDEs


Modern IDEs like IntelliJ IDEA, Eclipse, and NetBeans come with built-in debugging tools.
 Set breakpoints to pause the program at specific lines
 Step through code line by line
 Inspect variable values in real time
Tip: Use your IDE's debugger to find errors faster - it's more powerful than print statements alone!

Debugging Checklist
 Read the full error message, it often tells you exactly what's wrong
 Check if all variables are initialized before use
 Print variable values to trace the problem
 Watch for off-by-one errors in loops and arrays
 Comment out sections of code to find bugs

Java Exceptions
As mentioned in the Errors chapter, different types of errors can occur while running a program - such as coding
mistakes, invalid input, or unexpected situations.
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).

Exception Handling (try and catch)


Exception handling lets you catch and handle errors during runtime - so your program doesn't crash.
It uses different keywords:
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The try and catch keywords come in pairs:

Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Consider the following example:
This will generate an error, because myNumbers[10] does not exist.
public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
The output will be something like this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Main.main(Main.java:4)
Note: ArrayIndexOutOfBoundsException occurs when you try to access an index number that does not exist.
If an error occurs, we can use try...catch to catch the error and execute some code to handle it:

Example
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

The output will be:


Something went wrong.
Finally
The finally statement lets you execute code, after try...catch, regardless of the result:

Example
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}

The output will be:


Something went wrong.
The 'try catch' is finished.

ADVERTISEMENT

The throw keyword


The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are many exception types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:

Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access granted":
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
}
}

The output will be:


Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
If age was 20, you would not get an exception:

Example
checkAge(20);
The output will be:
Access granted - You are old enough!

Java Files
File handling is an important part of any application.
Java has several methods for creating, reading, updating, and deleting files.

Java File Handling


The File class from the java.io package, allows us to work with files.
To use the File class, create an object of the class, and specify the filename or directory name:

Example
import java.io.File; // Import the File class

File myObj = new File("filename.txt"); // Specify the filename


The File class has many useful methods for creating and getting information about files. For example:

Method Type Description

canRead() Boolean Tests whether the file is readable or not


canWrite() Boolean Tests whether the file is writable or not

createNewFile() Boolean Creates an empty file

delete() Boolean Deletes a file

exists() Boolean Tests whether the file exists

getName() String Returns the name of the file

getAbsolutePath() String Returns the absolute pathname of the file

length() Long Returns the size of the file in bytes

list() String[] Returns an array of the files in the directory

mkdir() Boolean Creates a directory

Java Create and Write To Files

Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the
file was successfully created, and false if the file already exists. Note that the method is enclosed in
a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be
created for some reason):

Example
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors

public class CreateFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
File created: filename.txt
To create a file in a specific directory (requires permission), specify the path of the file and use double
backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write the path, like:
/Users/name/filename.txt

Example
File myObj = new File("C:\\Users\\MyName\\filename.txt");

Write To a File
In the following example, we use the FileWriter class together with its write() method to write some text to the file
we created in the example above. Note that when you are done writing to the file, you should close it with
the close() method:

Example
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors

public class WriteToFile {


public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
Successfully wrote to the file.

Read a File
In the previous chapter, you learned how to create and write to a file.
In the following example, we use the Scanner class to read the contents of the text file we created in the previous
chapter:

Example
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
Files in Java might be tricky, but it is fun enough!

ADVERTISEMENT

Get File Information


To get more information about a file, use any of the File methods:

Example
import java.io.File; // Import the File class
public class GetFileInfo {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}
The output will be:
File name: filename.txt
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0
Note: There are many available classes in the Java API that can be used to read and write files in Java: FileReader,
BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream, etc. Which one to use
depends on the Java version you're working with and whether you need to read bytes or characters, and the size
of the file/lines etc.

Java Generics
Generics allow you to write classes, interfaces, and methods that work with different data types, without having
to specify the exact type in advance.
This makes your code more flexible, reusable, and type-safe.

Why Use Generics?


 Code Reusability: Write one class or method that works with different data types.
 Type Safety: Catch type errors at compile time instead of runtime.
 Cleaner Code: No need for casting when retrieving objects.

Generic Class Example


You can create a class that works with different data types using generics:
class Box<T> {
T value; // T is a placeholder for any data type

void set(T value) {


this.value = value;
}

T get() {
return value;
}
}

public class Main {


public static void main(String[] args) {
// Create a Box to hold a String
Box<String> stringBox = new Box<>();
stringBox.set("Hello");
System.out.println("Value: " + stringBox.get());

// Create a Box to hold an Integer


Box<Integer> intBox = new Box<>();
intBox.set(50);
System.out.println("Value: " + intBox.get());
}
}
T is a generic type parameter. It's like a placeholder for a data type.

 When you create a Box<String>, T becomes String.


 When you create a Box<Integer>, T becomes Integer.
This way, the same class can be reused with different data types without rewriting the code.

Generic Method Example


You can also create methods that work with any data type using generics:
public class Main {
// Generic method: works with any type T
public static <T> void printArray(T[] array) {
for (T item : array) {
System.out.println(item);
}
}

public static void main(String[] args) {


// Array of Strings
String[] names = {"Jenny", "Liam"};

// Array of Integers
Integer[] numbers = {1, 2, 3};

// Call the generic method with both arrays


printArray(names);
printArray(numbers);
}
}

Example Explained
 <T> is a generic type parameter - it means the method can work with any type: String, Integer, Double,
etc.
 The method printArray() takes an array of type T and prints every element.
 When you call the method, Java figures out what T should be based on the argument you pass in.
This is useful when you want to write one method that works with multiple types, instead of repeating code for
each one.

Bounded Types
You can use the extends keyword to limit the types a generic class or method can accept.
For example, you can require that the type must be a subclass of Number:
class Stats<T extends Number> {
T[] nums;

// Constructor
Stats(T[] nums) {
this.nums = nums;
}

// Calculate average
double average() {
double sum = 0;
for (T num : nums) {
sum += num.doubleValue();
}
return sum / nums.length;
}
}

public class Main {


public static void main(String[] args) {
// Use with Integer
Integer[] intNums = {10, 20, 30, 40};
Stats<Integer> intStats = new Stats<>(intNums);
System.out.println("Integer average: " + intStats.average());

// Use with Double


Double[] doubleNums = {1.5, 2.5, 3.5};
Stats<Double> doubleStats = new Stats<>(doubleNums);
System.out.println("Double average: " + doubleStats.average());
}
}
Even though int values are used in the first case, the .doubleValue() method converts them to double, so the result is
shown with a decimal point.

Example Explained
 <T extends Number>: Restricts T to only work with numeric types like Integer, Double, or Float.
 .doubleValue(): Converts any number to a double for calculation.
 Works for any array of numbers as long as the elements are subclasses of Number.

Generic Collections
Java Collections like ArrayList and HashMap use generics internally:
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
String fruit = list.get(0); // No need to cast

Summary
 Generics make your code flexible and type-safe.
 Use T or another letter to define a type placeholder.
 Generics can be applied to classes, methods, and interfaces.
 Use bounds to limit what types are allowed.

You might also like