What is Java OOP?
OOP stands for Object-Oriented Programming where java is a procedural programming. It is about writing procedures or methods to perform operations on the data. OOP is concerns creating objects that contain both data and methods.
Draftsbook goals For JAVA Teach:
- Java OOP
- Classes and objects
- Class Attributes
- Class Methods
- Method Parameters
- Method Overloading
- Scope
- recursion
- Constructor
- Modifiers
- Encapsulation
- Packages or API
- Inheritance
- Polymorphism
- Inner class
- Abstraction
- Interface
- Enums
- User Input
- Date and Time
- ArrayList
- LinkedList
- HashSet
- Iterator
- Wrapper Class
- Exceptions
- Threads
- Lambda
- Create read write file or Java File Handling
- Keyword
- string Methods
- String, StringBuffer and StringBuilder
- Overload vs Override
Object-oriented programming (OOP) has several advantages over procedural programming:
- is faster method or procedure
- and easier to execute code
- provides a clear structure for the programs
- helps to keep the Java code easier to maintain, modify and debug
- makes it possible to create full reusable applications with less code and shorter development time.
- easier to maintain flexibility.
What are Java Classes and Objects?
Classes and objects are the two main aspects of OOP (object-oriented programming). Look at the theoritical illustration to see the following difference between class and objects:
class
- Fruits
objects
- Apple
- Banana
- Mango
So, a class is a frame for objects, and an object is an instance of that class. When the individual objects or a single object is created, they inherit all the variables and methods from the class. Actually verything in Java is associated with classes and objects, along with its attributes and methods. For a Everything in Java is associated with classes and objects, along with its attributes and methods. For a real life example , a Tree is an object. example: leaves, leave_color, fruits_color etc are attributes of Tree.
Create a Class
To create a class, use the keyword”class”:
Tree.java
Create a class named “Tree” with a variable treeNumber:
public class Tree{
int treeNumber= 5;
}
Create an Object
In Java, an object is created from a class. We have already created the class named MyTreeClass, so now we can use this to create objects. To create an object of MyTreeClass, we specify the class name, followed by the object name, and use the keyword new:
Example
Create an object called “treeObj” and print the value of treeNumber:
public class Tree {
int treeNumber = 5;
public static void main(String[] args) {
Tree treeObj= new Tree();
System.out.println(treeObj.treeNumber );
}
}
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Tree:
public class Tree {
int treeNumber = 5;
public static void main(String[] args)
{
Tree treeObj1 = new Tree(); // Object 1
Tree treeObj2 = new Tree(); // Object 2
System.out.println(treeObj1.treeNumber );
System.out.println(treeObj2.treeNumber );
}
}
Using Multiple Classes
Multiple Classes means you can also create an object of a class and access the object in another class. This is frequently used for better decoration of classes. That is one class has all the attributes and methods, while the other class holds the main() method. Actually code to be executed. This is important to name the java file should be matched with the class name. In this example, we have created two files in the same directory/folder:
- Tree.java
- Treeotherclass.java
Tree.java
public class Tree
{
int treeNumber = 5;
}
Treeotherclass.java
class Treeotherclass {
public static void main(String[] args) {
Tree treeObj = new Tree();
System.out.println(treeObj.treeNumber );
}
}
Java Class Attributes
In the above class Tree.java we used the term “treeNumber ” for treeNumber in the example. It is actually an attribute of the class. Or you could define attribute as class attributes are variables within a class.
Example
Create a class called “Tree ” with two attributes: treeNumber and treeNumber_2:
public class Main {
int treeNumber= 5;
int treeNumber_2= 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 treeObj. We use the treeNumber attribute on the object to print its value:
Example
Create an object called “treeObj” and print the value of treeNumber :
public class Tree {
int treeNumber = 5;
public static void main(String[] args) {
Tree treeObj = new Tree ();
System.out.println(treeObj .treeNumber );
}
}
Modify Attributes
You can also modify attribute values:
Example
Set the value of treeNumber to 10:
public class Tree {
int treeNumber;
public static void main(String[] args) {
Tree myObj = new Tree();
treeObj.treeNumber = 10;
System.out.println(treeObj.treeNumber);
}
}
Or override existing values:
Example
Change the value of treeNumberto 20:
public class Tree{
int treeNumber = 10;
public static void main(String[] args) {
treeNumber treeObj = new treeNumber();
treeObj.treeNumber = 20; // treeNumber is now 20
System.out.println(treeObj.treeNumber);
}
}
Final keyword
If you don’t want the ability to override existing values, declare the attribute as final:
Example
public class Tree
{
final int treeNumber = 10;
public static void main(String[] args)
{
Tree treeObj = new Tree();
treeObj.treeNumber = 20; // will generate an error: cannot assign a value to a final variable
System.out.println(treeObj.treeNumber);
}
}
Multiple Objects
TO create multiple objects of one class, you can change the attribute values in one object, without changing the attribute values in the other:
Example
Change the value of treeNumber to 20 in treeObj2, and leave Tree in treeObj1 unchanged:
public class Tree
{
int treeNumber = 5;
public static void main(String[] args) {
Tree treeObj1 = new Tree(); // Object 1
Tree treeObj2 = new Tree(); // Object 2
treeObj2.treeNumber = 20;
System.out.println(treeObj1.treeNumber ); // Outputs 5
System.out.println(treeObj2.treeNumber ); // Outputs 20
}
}
Multiple Attributes
You can specify as many attributes as you want:
Example
public class Tree
{
String fname = “John”;
String lname = “Joe”;
int age = 21;
public static void main(String[] args) {
Tree myObj = new Tree();
System.out.println(“Name: ” + myObj.fname + ” ” + myObj.lname);
System.out.println(“Age: ” + myObj.age);
}
}
Java Constructors
In Java, a constructor 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 Tree
{
int treeNumber = 5; // Create a class attribute
// Create a class constructor for the Main class
public Tree() {
treeNumber = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
Tree myObj = new Tree(); // Create an object of class Tree. This will call the constructor.
System.out.println(myObj.x); // Print the value of treeNumber
}
}
// Outputs 5
It is keep to mind 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. Even if, all classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. But, 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 Tree{
int x;
public Tree(int y) {
x = y;
}
public static void main(String[] args) {
Tree myObj = new Tree(5);
System.out.println(myObj.x);
}
}
// Outputs 5
Java Modifiers
Modifiers 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. |
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. |
protected | The code is accessible in the same package and subclasses and superclasses in the Inheritance. |
Non-Access Modifiers
For classes, you can use either final or abstract:
Modifier | Description |
final | The class cannot be inherited by other classes |
abstract | The class cannot be used to create objects . To access an abstract class, it must be inherited from another class. |
For attributes and methods, you can use the one of the following:
Modifier | Description |
final | Attributes and methods cannot be overridden/modified |
static | Attributes and methods belongs to the class, rather than an object |
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 or inherited from other class. |
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
// abstract class
abstract class Tree {
public String fname = “Leaves”;
public int age = 24;
public abstract void study(); // abstract method
}
// Subclass (inherit from Tree )
class Green extends Tree{
public int plantYear = 2018;
public void plant() { // the body of the abstract method is provided here
System.out.println(“Planting all the year long”);
}
}
// End code from filename: Tree .java
// Code from filename: TreeSecond.java
class TreeSecond {
public static void main(String[] args) {
// create an object of the Student class (which inherits attributes and methods from Tree )
Green myObj = new Green ();
System.out.println(“Name: ” + myObj.fname);
System.out.println(“Age: ” + myObj.age);
System.out.println(“Plantation Year: ” + myObj.plantYear );
myObj.plant(); // call abstract method
}
}
See more Topic on Java OOP with real-time example
Nested class in JAVA with EXAMPLES
What is the defference between String, StringBuffer and StringBuilder.
Java Interface tutorials with Example.