0% found this document useful (0 votes)
56 views58 pages

Oop PDF File (Class 10 To 15)

OOP stands for Object-Oriented Programming. In OOP, programs are designed around objects that contain data and code to manipulate the data. This differs from procedural programming which focuses on writing procedures or methods. OOP has advantages like being faster, providing clear structure, reducing repeated code, and making code easier to maintain through reuse. Everything in Java is associated with classes and objects which have attributes and methods. A class defines the blueprint while objects are instances of a class. Methods define actions that can be performed on objects.

Uploaded by

Nasir Khan
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)
56 views58 pages

Oop PDF File (Class 10 To 15)

OOP stands for Object-Oriented Programming. In OOP, programs are designed around objects that contain data and code to manipulate the data. This differs from procedural programming which focuses on writing procedures or methods. OOP has advantages like being faster, providing clear structure, reducing repeated code, and making code easier to maintain through reuse. Everything in Java is associated with classes and objects which have attributes and methods. A class defines the blueprint while objects are instances of a class. Methods define actions that can be performed on objects.

Uploaded by

Nasir Khan
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/ 58

Java OOP

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.

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts:

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation

System.out.println(myObj.x);
}
}
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
System.out.println(myObj.x);
}
}
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.

You will learn much more about classes and objects in the next chapter.

Java Classes and Objects

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:

System.out.println(myObj.x);
}
}
Main.java

Create a class named "Main" with a variable x:

public class Main {


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.

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:

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(myObj.x);
}
}
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:

You will learn much more about classes and objects in the next chapters.

System.out.println(myObj.x);
}
}
Java Class AttributesJava Class
Methods

Java Class Attributes

In the previous chapter, we used the term "variable" for x in the example (as shown
below). It isactually 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 Mainclass, with the name myObj. We use the

x attribute on the object to print its value:

Example

System.out.println(myObj.x);
}
}
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-1

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

Example-2

Change the value of xto 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:

System.out.println(myObj.x);
}
}
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);
}
}
The final keyword is useful when you want a variable to always store the same value, like PI
(3.14159...).

The finalkeyword is called a "modifier".

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 xto 25 in myObj2, and leave xin myObj1unchanged:

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
thatthey 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'sname 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 staticmethod, 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 staticand publicmethods:


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 bya semicolon (;).

A class must have a matching filename (Mainand Main.java).

Using Multiple Classes

Like we specified in the Classes chapter, it is a good practice to create an object of a class
andaccess 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()
methodmyCar.speed(200); // Call the speed() method
}
}

After compilation the output will be:

The car is going as fast as it can!


Max speed is: 200

Review of course materials till now.

14. Java Inheritance

Java Inheritance (Subclass and Superclass)

Inheritance is a mechanism wherein a new class is derived from an existing class. In Java, classes may
inherit or acquire the properties and methods of other classes. A class derived from another class is
called a subclass, whereas the class from which a subclass is derived is called a 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

fromTo inherit from a class, use the extends keyword.

In the example below, the Carclass (subclass) inherits the attributes and methods from the

Vehicleclass (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);
}
}
// Tuut, tuut!
// Ford Mustang
Did you notice the protectedmodifier in Vehicle?

We set the brand attribute in Vehicle to a protectedaccess 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
youcreate 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 {


...
}]

Example:

final class Vehicle {

protected String brand = "Ford";

public void honk() {

System.out.println("Tuut, tuut!");

class Main extends Vehicle {


private String modelName = "Mustang";

public static void main(String[] args) {


Main myFastCar = new Main();

myFastCar.honk();

System.out.println(myFastCar.brand + " " + myFastCar.modelName);

// Output

Main.java:9: error: cannot inherit from final Vehicle


class Main extends Vehicle {
^
1 error)

15. Java Polymorphism

Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are
related toeach other by inheritance.

In Java, polymorphism refers to the ability of a class to provide different implementations of


a method, depending on the type of object that is passed to the method. To put it simply,
polymorphism in Java allows us to perform the same action in many different ways.

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 usto perform a single action in different ways.

For example, think of a superclass called Animalthat 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");
}
}
Now we can create Pigand Dogobjects 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();
}
}

// The animal makes a sound


// The pig says: wee wee

// The dog says: bow wow

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

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

The difference between inheritance and polymorphism


In inheritance, we
create new classes Method?
that inherit features
A method in Java is a block of code that, when called, performs
of the superclass
specific actions mentioned in it. Forinstance, if you have written
while polymorphism
instructions to draw a circle in the method, it will do that task. You
decides what form of
can insert values or parameters into methods, and they will only be
method to execute.
executed when called.
Inheritance applies to
classes, whereas
polymorphism applies
to methods.

Inheritance is one 16. Java Classes


in which a new
class is created
(derived class)
that inherits the
features from the
already existing
class (Base class).
Whereas
polymorphism is
that which can be
defined in
multiple forms. It
is basically
applied to classes.

Class?

A class can also be


called a logical
template to create the
objects that share
common properties
and methods. For
example, an Employee
class may contain all
the employee details in
the form of variables
and methods.
Class, Abstraction, Interfaces

A class in Java is a logical template to create objects that share common


properties and methods. Hence, all objects in a given class will have the
same methods or properties. For example: in the real world, a specific cat is
an object of the “cats” class.

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.

An inner class in Java is defined as a class that is declared inside another


class. Inner classes are often used to create helper classes, such as views
or adapters that are used by the outer class.
Inner classes can also be used to create nested data structures, such as a
linked list.

Java Inner Classes


In Java, it is also possible to nest classes (a class within a class). The
purpose of nested classes is to group classes that belong together, which
makes your code more readable and maintainable.

To access the inner class, create an object of the outer class, and then
create an object of the inner class:

Example
class OuterClass {
int x = 10;

class InnerClass {
int y = 5;

public class Main {

public static void main(String[] args) {


OuterClass myOuter = new OuterClass();

OuterClass.InnerClass myInner = myOuter.new InnerClass();


System.out.println(myInner.y + myOuter.x);

// Outputs 15 (5 + 10)
Private Inner Class
Unlike a "regular" class, an inner class can be private or protected. If you
don't want outside objects to access the inner class, declare the class as
private:

Example
class OuterClass {
int x = 10;

private class InnerClass {


int y = 5;

public class Main {

public static void main(String[] args) {


OuterClass myOuter = new OuterClass();

OuterClass.InnerClass myInner = myOuter.new InnerClass();


System.out.println(myInner.y + myOuter.x);

Note: If you try to access a private inner class from an outside class, an
error occurs:

Main.java:13: error: OuterClass.InnerClass has private access in OuterClass


OuterClass.InnerClass myInner = myOuter.new InnerClass();

Static Inner Class


An inner class can also be static, which means that you can access it without
creating an object of the outer class:

Example
class OuterClass {
int x = 10;

static class InnerClass {


int y = 5;
}

public class Main {

public static void main(String[] args) {

OuterClass.InnerClass myInner = new OuterClass.InnerClass();


System.out.println(myInner.y);

// Outputs 5
Note: just like static attributes and methods, a static inner class does not have access to members
of the outer class.

Access Outer Class From Inner Class


One advantage of inner classes, is that they can access attributes and methods
of the outer class:

Example
class OuterClass {
int x = 10;

class InnerClass {

public int myInnerMethod() {


return x;

public class Main {

public static void main(String[] args) {


OuterClass myOuter = new OuterClass();

OuterClass.InnerClass myInner = myOuter.new InnerClass();


System.out.println(myInner.myInnerMethod());

// Outputs 10

17. Java Abstraction

Abstraction is a process of hiding the implementation details and showing


only functionality to the user. Another way, it shows only essential things
to the user and hides the internal details, for example, sending SMS where you
type the text and send the message.
Data abstraction in Java helps the developers hide the code complications
from the end-user by reducing the project's complete characteristics to only
the necessary components.

Abstraction is a technique of hiding unnecessary details from the user.


The user is only given access to the details that are relevant. Vehicle
operations or ATM operations are classic examples of abstractions in the
real world.
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:

Example:

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, which you will learn
more about in the next chapter.
18. Java Interface

Interfaces
An interface is a completely "abstract class" that is used to group related methods with
emptybodies.

An interface is an abstract "class" that is used to group related methods


with "empty" bodies: To access the interface methods, the interface must be
"implemented" (kinda like inherited) by another class with the implements
keyword (instead of extends ).

An interface in the Java programming language is an abstract type that is


used to declare a behavior that classes must implement. They are similar to
protocols. Interfaces are declared using the interface keyword, and may only
contain method signature and constant declarations.

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
emptybodies:

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
notpossible 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
examplebelow).

In summary, the Abstract class and Interface both are used to have abstraction. An
abstract class contains an abstract keyword on the declaration whereas an Interface is a
sketch that is used to implement a class.

Encapsulation and Enumeration

19. Java Encapsulation


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

Encapsulation in Java is the process by which data (variables) and the code that
acts upon them (methods) are integrated as a single unit. By encapsulating a
class'svariables, other classes cannot access them, and only the methods of the
class can access them.

Encapsulation is a way to restrict the direct access to some components of an


object, so users cannot access state values for all of the variables of a particular
object. Encapsulation can be used to hide both data members and data functions
ormethods associated with an instantiated class or object.

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-1:
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-2:
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:

Instead, we use the getName() and setName() methods to access and update the variable:

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
20. Java Enums

Enums

An enum is a special "class" that represents a group of constants (unchangeable


variables, like
final variables).

An enumeration (enum for short) in Java is a special data type which contains
a set of predefined constants. You'll usually use an enum when dealing with
values that aren't required to change, like days of the week, seasons of the
year, colors, and so on.

Enumeration means counting or reciting numbers or a numbered list. A


waiter's lengthy enumeration of all the available salad dressings might
seem a little hostile if he begins with a deep sigh. When you're reciting
a list of things, it's enumeration.

To create an enum, use the enum keyword (instead of class or


interface), and separate the constants with a comma. Note that they
should be in uppercase letters:

Example
enum Level {
LOW,
MEDIUM,
HIGH

You can access enum constants with the dot

syntax: Level myVar = Level.MEDIUM;

Note: Enum is short for "enumerations", which means "specifically listed".

Enum inside a Class


You can also have an enum inside a class:

Example
public class Main {
enum Level {

LOW,
MEDIUM,
HIGH

}
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
System.out.println(myVar);
}

The output will be:

MEDIUM

Enum in a Switch Statement


Enums are often used in switch statements to check for corresponding values:

Example
enum Level {
LOW,
MEDIUM,
HIGH

public class Main {

public static void main(String[] args) {


Level myVar = Level.MEDIUM;

switch(myVar) {
case LOW:

System.out.println("Low level");
break;

case MEDIUM:
System.out.println("Medium level");

break;
case HIGH:

System.out.println("High level");
break;

The output will be:

Medium level
Loop Through an Enum
The enum type has a values() method, which returns an array of all enum
constants. This method is useful when you want to loop through the
constants of an enum:

Example
for (Level myVar : Level.values()) {
System.out.println(myVar);

}
The output will be:

LOW
MEDIUM
HIGH

Note: Difference between Enums and Classes

An enum can, just like a class, have attributes and methods. The only
difference is that enum constants are public, static and final (unchangeable
- cannot be overridden).

An enum cannot be used to create objects, and it cannot extend other


classes (but it can implement interfaces).

Why And When To Use Enums?

Use enums when you have values that you know aren't going to change, like
month days, days, colors, deck of cards, etc.

21. Java Exceptions


Definition: An exception is an event, which occurs during the execution of
a program, that disrupts the normal flow of the program's instructions.
When an error occurs within a method, the method creates an object and
hands it off to the runtime system.

An exception is an event that occurs during the execution of a program that


disrupts the normal flow of the program's instructions. In Java, exceptions
are objects that describe an exceptional (error) condition that has occurred
in a piece of code.
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).

Java try and catch


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)

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.

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
typesavailable 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!

Test Yourself With Exercises


Exercise-1:
Insert the missing parts to handle the error in the code below.

int[] myNumbers = {1, 2, 3};


System.out.println(myNumbers[10]);

} (Exception e) {
System.out.println("Something went wrong.");

Exercise-2:

Insert the missing keyword to execute code, after try..catch, regardless of the
result.

try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);

} catch (Exception e) { System.out.println("Something


went wrong.");

} {

System.out.println("The 'try catch' is finished.");

Java file handling, Java GUI

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 Fileclass, 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 Fileclass 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
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

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 Scannerclass 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!


Delete a File

To delete a file in Java, use the delete() method:

Example
import java.io.File; // Import the File class
public class DeleteFile {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}

The output will be:

Deleted the file: filename.txt

What is GUI in Java?

GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for Java
applications. It is mainly made of graphical components like buttons, labels, windows, etc.
through which the user can interact with an application. GUI plays an important role to build
easy interfaces for Java applications.

How to Make a GUI in Java with Example

Now in this Java GUI Tutorial, let’s understand how to create


a GUI in Java with Swings in Java examples.

Step 1) Copy code into an editor

In first step Copy the following

code into an editor. Example:

import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane of
frame
frame.setVisible(true);
}
}

Step 2) Run the code

Next step, Save, Compile, and Run the code


Step 3) Copy following code into an editor

Now let’s Add a Button to our frame. Copy following

code into an editor from given Java UI Example:

import
javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First
GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new
JButton("Press");
frame.getContentPane().add(button1);
frame.setVisible(true);
}
}

Step 4) Execute the code

Next, Execute the code. You will get a big button.

You might also like