Oop PDF File (Class 10 To 15)
Oop PDF File (Class 10 To 15)
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.
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.
• 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
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/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.
Create a Class
To create a class, use the keyword class:
System.out.println(myObj.x);
}
}
Main.java
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
Multiple Objects
You can create multiple objects of one 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/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);
}
}
You will learn much more about classes and objects in the next chapters.
System.out.println(myObj.x);
}
}
Java Class AttributesJava Class
Methods
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
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
Example
System.out.println(myObj.x);
}
}
Create an object called "myObj" and print the value of x:
int x = 5;
System.out.println(myObj.x);
}
}
Modify Attributes
Example-1
Example-2
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;
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...).
Multiple Objects
If you create multiple objects of one class, you can change the attribute values in one
object,without affecting the attribute values in the other:
Example
Multiple Attributes
Example-
You learned from the Java Methods chapter that methods are declared within a class, and
thatthey are used to perform certain actions:
Example
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
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
// 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
Create a Car object named myCar. Call the fullThrottle()and speed()methods on the myCar
object, and run the program:
3) The fullThrottle() method and the speed() method will print out some text, when they are
called.
4) The speed() method accepts an int parameter called maxSpeed - we will use this in 8).
5) In order to use the Main class and its methods, we need to create an object of the Main
Class.
6) Then, go to the main() method, which you know by now is a built-in Java method that runs
your program (any code inside main is executed).
7) By using the new keyword we created an object with the name myCar.
8) Then, we call the fullThrottle() and speed() methods on the myCar object, and run the
program using the name of the object (myCar), followed by a dot (.), followed by the name of
the method (fullThrottle(); and speed(200);). Notice that we add an int parameter of 200
inside the speed() method.
Remember that..
The dot (.) is used to access the object's attributes and methods.
To call a method in Java, write the method name followed by a set of parentheses (),
followed bya semicolon (;).
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!");
}
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
}
}
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:
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!");
}
}
// 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.
- 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.
Example:
System.out.println("Tuut, tuut!");
myFastCar.honk();
// Output
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are
related toeach 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 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");
}
}
Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
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();
}
}
- It is useful for code reusability: reuse attributes and methods of an existing class when
youcreate a new class.
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.
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;
// 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;
Note: If you try to access a private inner class from an outside class, an
error occurs:
Example
class OuterClass {
int x = 10;
// Outputs 5
Note: just like static attributes and methods, a static inner class does not have access to members
of the outer class.
Example
class OuterClass {
int x = 10;
class InnerClass {
// Outputs 10
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:
System.out.println("Zzz");
}
From the example above, it is not possible to create an object of the Animal class:
Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.
Example
// Abstract class
abstract class Animal {
// Regular method
public void sleep() {
System.out.println("Zzz");
class Main {
myPig.sleep();
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 a completely "abstract class" that is used to group related methods with
emptybodies:
Example
// interface
interface Animal {
Example
// Interface
interface Animal {
class Main {
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)
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 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.
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 {
// Getter
// Setter
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.
Example-2:
public class Main {
System.out.println(myObj.name); // error
If the variable was declared as public, we would expect the following output:
John
Instead, we use the getName() and setName() methods to access and update the variable:
// 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 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.
Example
enum Level {
LOW,
MEDIUM,
HIGH
Example
public class Main {
enum Level {
LOW,
MEDIUM,
HIGH
}
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
System.out.println(myVar);
}
MEDIUM
Example
enum Level {
LOW,
MEDIUM,
HIGH
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;
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
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).
Use enums when you have values that you know aren't going to change, like
month days, days, colors, deck of cards, etc.
When an error occurs, Java will normally stop and generate an error message.
The technical term for this is: Java will throw an exception (throw an error).
Syntax
try {
catch(Exception e) {
If an error occurs, we can use try...catch to catch the error and execute
some code to handle it:
Example
public class Main {
} catch (Exception e) {
System.out.println("Something went wrong.");
}
The finally statement lets you execute code, after try...catch, regardless of the result:
Example
public class Main {
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
The throw statement is used together with an exception type. There are many exception
typesavailable in Java: ArithmeticException, FileNotFoundException,
ArrayIndexOutOfBoundsException, SecurityException, etc:
Example
else {
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
Example
checkAge(20);
} (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]);
} {
Java Files
File handling is an important part of any application.
Java has several methods for creating, reading, updating, and deleting files.
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
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
Example
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
Write To a File
Example
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
Read 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
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.");
}
}
}
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.
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);
}
}
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);
}
}