Oop
Oop
1
Non-Access Modifiers .......................................................................................................................... 19
Final ........................................................................................................................................................ 20
Example............................................................................................................................................. 20
Static ....................................................................................................................................................... 21
Example............................................................................................................................................. 21
Abstract .................................................................................................................................................. 22
Example............................................................................................................................................. 22
Encapsulation ........................................................................................................................................ 24
Get and Set ............................................................................................................................................ 24
Example............................................................................................................................................. 24
Java Packages & API ............................................................................................................................ 25
Built-in Packages .................................................................................................................................. 25
Syntax ................................................................................................................................................ 26
Import a Class ....................................................................................................................................... 26
Example............................................................................................................................................. 26
Example............................................................................................................................................. 26
Import a Package .................................................................................................................................. 27
Example............................................................................................................................................. 27
User-defined Packages ........................................................................................................................ 27
Example............................................................................................................................................. 27
MyPackageClass.java ..................................................................................................................... 28
Java Inheritance ...................................................................................................................................... 28
Java Inheritance (Subclass and Superclass) ....................................................................................... 28
Example............................................................................................................................................. 28
The final Keyword ................................................................................................................................. 30
Java Polymorphism ............................................................................................................................... 30
Example............................................................................................................................................. 31
Example............................................................................................................................................. 31
Java Abstract Classes and Methods ................................................................................................... 33
Example............................................................................................................................................. 34
Java Interface......................................................................................................................................... 35
2
Example............................................................................................................................................. 35
Example............................................................................................................................................. 36
Multiple Interfaces ................................................................................................................................ 37
Example............................................................................................................................................. 37
Loops ...................................................................................................................................................... 38
Java While Loop .................................................................................................................................... 39
Syntax ................................................................................................................................................ 39
Example............................................................................................................................................. 39
The Do/While Loop .............................................................................................................................. 39
Syntax ................................................................................................................................................ 40
Example............................................................................................................................................. 40
Java For Loop ........................................................................................................................................ 40
Syntax ................................................................................................................................................ 40
Example............................................................................................................................................. 41
What is OOP?
What is Java?
3
It is used for:
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
It is one of the most popular programming language in the world
It has a large demand in the current job market
It is easy to learn and simple to use
It is open-source and free
It is secure, fast and powerful
It has a huge community support (tens of millions of developers)
Java is an object oriented language which gives a clear structure to programs
and allows code to be reused, lowering development costs
As Java is close to C++ and C#, it makes it easy for programmers to switch to
Java or vice versa
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
System.out.println("Hello World");
Example explained
Every line of code that runs in Java must be inside a class. In our example, we named
the class Main. A class should always start with an uppercase first letter.
4
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 is required and you will see it in every Java program:
Any code inside the main() method will be executed. Don't worry about the keywords
before and after main. 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:
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 System, out and println(). 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 (;).
5
Method Overloading
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.
With method overloading, multiple methods can have the same name with
different parameters:
Example
int myMethod(int x)
float myMethod(float x)
Consider the following example, which have two methods that add numbers of
different type:
Example
static int plusMethodInt(int x, int y) {
return x + y;
return x + y;
6
public static void main(String[] args) {
Run example »
Instead of defining two methods that should do the same thing, it is better to
overload one.
In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.
7
14. obj.run();
15. }
16. }
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.
1. class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
8
In this tutorial, we will learn about Java exceptions, it's types, and the difference between
checked and unchecked exceptions.
JavaExceptionExample.java
There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
9
2. Type of exception Using Using throws keyword,
throw keyword, we can we can declare both
only propagate unchecked checked and
exception i.e., the checked unchecked exceptions.
exception cannot be However, the throws
propagated using throw keyword can be used to
only. propagate checked
exceptions only.
10
}
}
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}
Java Methods
❮ PreviousNext ❯
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:
11
Example
Create a method inside MyClass:
// code to be executed
Example Explained
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.
Object Definitions:
12
o The object is an entity which has state and behavior.
o The object is an instance of a class.
Objects An entity that has state and behavior is known as an object e.g., chair,
bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The
example of an intangible object is the banking system.
Create a Class
To create a class, use the keyword class:
MyClass.java
Create a class named "MyClass" with a variable x:
int x = 5;
Remember from the Java Syntax chapter that a class should always start with
an uppercase first letter, and that the name of the java file should match the
class name.
13
Create an Object
In Java, an object is created from a class. We have already created the class
named MyClass, so now we can use this to create objects.
To create an object of MyClass, 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:
int x = 5;
System.out.println(myObj.x);
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:
14
int x; // Create a class attribute
public MyClass() {
// Outputs 5
Run example »
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.
15
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 MyClass {
int x;
public MyClass(int y) {
x = y;
System.out.println(myObj.x);
// Outputs 5
Run example »
Example
public class Car {
int modelYear;
String modelName;
16
public Car(int year, String name) {
modelYear = year;
modelName = name;
Modifiers
By now, you are quite familiar with the public keyword that appears in almost all
of our examples:
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
17
For classes, you can use either public or default:
default The class is only accessible by classes in the same package. This is used Try it
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:
private The code is only accessible within the declared class Try it
»
default The code is only accessible in the same package. This is used when Try it
you don't specify a modifier. You will learn more about packages in »
the Packages chapter
18
protected The code is accessible in the same package and subclasses. You will Try it
learn more about subclasses and superclasses in the Inheritance »
chapter
Non-Access Modifiers
For classes, you can use either final or abstract:
final The class cannot be inherited by other classes (You will learn more Try
about inheritance in the Inheritance chapter) it »
abstract The class cannot be used to create objects (To access an abstract class, Try
it must be inherited from another class. You will learn more about it »
inheritance and abstraction in
the Inheritance and Abstraction chapters)
For attributes and methods, you can use the one of the following:
Modifier Description
19
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
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 MyClass {
20
public static void main(String[] args) {
System.out.println(myObj.x);
Run example »
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:
// Static method
21
// Public method
// Main method
Run example »
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: Person.java
22
// abstract class
abstract class Person {
class MyClass {
23
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:
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 {
// Getter
return name;
24
// Setter
this.name = newName;
Example explained
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.
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.
25
To use a class or a package from the library, you need to use
the import keyword:
Syntax
import package.name.Class; // Import a single class
Import a Class
If you find a class you want to use, for example, the Scanner class, which is
used to get user input, write the following code:
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");
26
String userName = myObj.nextLine();
Run example »
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.*;
Run example »
User-defined Packages
To create your own package, you need to understand that Java uses a file
system directory to store them. Just like folders on your computer:
Example
└── root
└── mypack
└── MyPackageClass.java
27
MyPackageClass.java
package mypack;
class MyPackageClass {
System.out.println("This is my package!");
Java Inheritance
❮ PreviousNext ❯
In the example below, the Car class (subclass) inherits the attributes and
methods from the Vehicle class (superclass):
Example
class Vehicle {
28
System.out.println("Tuut, tuut!");
// 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
Run example »
29
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.
...
...
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.
30
Example
class Animal {
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 {
31
System.out.println("The animal makes a sound");
class MyMainClass {
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
32
}
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).
System.out.println("Zzz");
From the example above, it is not possible to create an object of the Animal
class:
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:
33
Remember from the Inheritance chapter that we use the extends keyword to
inherit from a class.
Example
// Abstract class
// Regular method
System.out.println("Zzz");
class MyMainClass {
myPig.animalSound();
34
myPig.sleep();
Java Interface
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
Example
// interface
interface Animal {
35
Example
// Interface
interface Animal {
System.out.println("Zzz");
class MyMainClass {
myPig.animalSound();
myPig.sleep();
36
}
Run example »
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 {
37
interface SecondInterface {
System.out.println("Some text..");
class MyMainClass {
myObj.myMethod();
myObj.myOtherMethod();
Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code
more readable.
38
Java While Loop
The while loop loops through a block of code as long as a specified condition
is true:
Syntax
while (condition) {
In the example below, the code in the loop will run, over and over again, as
long as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
Run example »
Note: Do not forget to increase the variable used in the condition, otherwise
the loop will never end!
39
Syntax
do {
while (condition);
The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:
Example
int i = 0;
do {
System.out.println(i);
i++;
Run example »
Do not forget to increase the variable used in the condition, otherwise the loop
will never end!
Syntax
for (statement 1; statement 2; statement 3) {
40
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
for (int i = 0; i < 5; i++) {
System.out.println(i);
Run example »
Example explained
Statement 2 defines the condition for the loop to run (i must be less than 5). If
the condition is true, the loop will start over again, if it is false, the loop will
end.
Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
41