Part 1: Java OOP and its feature with example

JAVA | 0 comments

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:

  1. Java OOP 
  2. Classes and objects
  3. Class Attributes
  4. Class Methods
  5. Method Parameters
  6. Method Overloading
  7. Scope
  8. recursion
  9. Constructor
  10. Modifiers
  11. Encapsulation
  12. Packages or API
  13. Inheritance
  14. Polymorphism
  15. Inner class
  16. Abstraction
  17. Interface
  18. Enums
  19. User Input
  20. Date and Time
  21. ArrayList
  22. LinkedList
  23. HashSet
  24. Iterator
  25. Wrapper Class
  26. Exceptions
  27. Threads
  28. Lambda
  29. Create read write file or Java File Handling 
  30. Keyword
  31. string Methods
  32. String, StringBuffer and StringBuilder
  33. 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:

  1. Tree.java
  2. 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:

  1. Access Modifiers – controls the access level
  2. 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.

JAVA abstract class with EXAMPLES

What Does Method Signature Mean in Java?

Chapter 4 Relational Algebra

Relational Algebra The part of mathematics in which letters and other general symbols are used to represent numbers and quantities in formula and equations. Ex: (x + y) · z = (x · z) + (y · z). The main application of relational algebra is providing a theoretical...

Chapter 3 Components of the Database System Environment

Components of the Database System Environment There are five major components in the database system environment and their interrelationships are. Hardware Software Data Users Procedures Hardware:  The hardware is the actual computer system used for keeping and...

Chapter 2: Database Languages and their information

Database Languages A DBMS must provide appropriate languages and interfaces for each category of users to express database queries and updates. Database Languages are used to create and maintain database on computer. There are large numbers of database languages like...

Database basic overview

What is DBMS? A Database Management System (DBMS) is a collection of interrelated data and a set of programs to access those data. Database management systems (DBMS) are computer software applications that interact with the user, other applications, and the database...

Laravel – Scopes (3 Easy Steps)

Scoping is one of the superpowers that eloquent grants to developers when querying a model. Scopes allow developers to add constraints to queries for a given model. In simple terms laravel scope is just a query, a query to make the code shorter and faster. We can...

CAMBRIDGE IELTS 17 TEST 3

READING PASSAGE 1: The thylacine Q1. carnivorous keywords: Looked like a dog had series of stripes ate, diet ate an entirely 1 .......................................... diet (2nd paragraph 3rd and 4th line) 1st and 2nd paragraph, 1st  paragraph,resemblance to a...

You may find interest following article

Chapter 4 Relational Algebra

Relational Algebra The part of mathematics in which letters and other general symbols are used to represent numbers and quantities in formula and equations. Ex: (x + y) · z = (x · z) + (y · z). The main application of relational algebra is providing a theoretical foundation for relational databases, particularly query languages for such databases. Relational algebra...

Chapter 3 Components of the Database System Environment

Components of the Database System Environment There are five major components in the database system environment and their interrelationships are. Hardware Software Data Users Procedures Hardware:  The hardware is the actual computer system used for keeping and accessing the database. Conventional DBMS hardware consists of secondary storage devices, usually...

Chapter 2: Database Languages and their information

Database Languages A DBMS must provide appropriate languages and interfaces for each category of users to express database queries and updates. Database Languages are used to create and maintain database on computer. There are large numbers of database languages like Oracle, MySQL, MS Access, dBase, FoxPro etc. Database Languages: Refers to the languages used to...

Database basic overview

What is DBMS? A Database Management System (DBMS) is a collection of interrelated data and a set of programs to access those data. Database management systems (DBMS) are computer software applications that interact with the user, other applications, and the database itself to capture and analyze data. Purpose of Database Systems The collection of data, usually...

Laravel – Scopes (3 Easy Steps)

Scoping is one of the superpowers that eloquent grants to developers when querying a model. Scopes allow developers to add constraints to queries for a given model. In simple terms laravel scope is just a query, a query to make the code shorter and faster. We can create custom query with relation or anything with scopes. In any admin project we need to get data...

CAMBRIDGE IELTS 17 TEST 3

READING PASSAGE 1: The thylacine Q1. carnivorous keywords: Looked like a dog had series of stripes ate, diet ate an entirely 1 .......................................... diet (2nd paragraph 3rd and 4th line) 1st and 2nd paragraph, 1st  paragraph,resemblance to a dog. … dark brown stripes over its back, beginning at the rear of the body and extending onto the...

CAMBRIDGE IELTS 17 TEST 4

PASSAGE 1 Q1 (False) (Many Madagascan forests are being destroyed by attacks from insects.) Madagascar's forests are being converted to agricultural land at a rate of one percent every year. Much of this destruction is fuelled by the cultivation of the country's main staple crop: rice. And a key reason for this destruction is that insect pests are destroying vast...

Cambridge IELTS 16 Test 4

Here we will discuss pros and cons of all the questions of the passage with step by step Solution included Tips and Strategies. Reading Passage 1 –Roman Tunnels IELTS Cambridge 16, Test 4, Academic Reading Module, Reading Passage 1 Questions 1-6. Label the diagrams below. The Persian Qanat Method 1. ………………………. to direct the tunnelingAnswer: posts – First...

Cambridge IELTS 16 Test 3

Reading Passage 1: Roman Shipbuilding and Navigation, Solution with Answer Key , Reading Passage 1: Roman Shipbuilding and Navigation IELTS Cambridge 16, Test 3, Academic Reading Module Cambridge IELTS 16, Test 3: Reading Passage 1 – Roman Shipbuilding and Navigation with Answer Key. Here we will discuss pros and cons of all the questions of the...

Cambridge IELTS 16 Test 2

Reading Passage 1: The White Horse of Uffington, Solution with Answer Key The White Horse of Uffington IELTS Cambridge 16, Test 2, Academic Reading Module, Reading Passage 1 Cambridge IELTS 16, Test 2: Reading Passage 1 – The White Horse of Uffington  with Answer Key. Here we will discuss pros and cons of all the questions of the passage with...

Cambridge IELTS 16 Test 1

Cambridge IELTS 16, Test 1, Reading Passage 1: Why We Need to Protect Bolar Bears, Solution with Answer Key Cambridge IELTS 16, Test 1: Reading Passage 1 – Why We Need to Protect Bolar Bears with Answer Key. Here we will discuss pros and cons of all the questions of the passage with step by step...

Cambridge IELTS 15 Reading Test 4 Answers

PASSAGE 1: THE RETURN OF THE HUARANGO QUESTIONS 1-5: COMPLETE THE NOTES BELOW. 1. Answer: water Key words:  access, deep, surface Paragraph 2 provides information on the role of the huarango tree: “it could reach deep water sources”. So the answer is ‘water’. access = reach Answer: water. 2. Answer: diet Key words: crucial,...

Cambridge IELTS 15 Reading Test 3 Answers

PASSAGE 1: HENRY MOORE (1898 – 1986 ) QUESTIONS 1-7: DO THE FOLLOWING STATEMENTS AGREE WITH THE INFORMATION GIVEN IN READING PASSAGE 1? 1. Answer: TRUE Key words: leaving school, Moore, did, father, wanted It is mentioned in the first paragraph that “After leaving school, Moore hoped to become a sculptor, but instead he complied with his father’s...

Cambridge IELTS 15 Reading Test 2 Answers 

PASSAGE 1: COULD URBAN ENGINEERS LEARN FROM DANCE ?  QUESTIONS 1- 6: READING PASSAGE 1 HAS SEVEN PARAGRAPHS, A-G. 1. Answer: B Key words: way of using dance, not proposing By using the skimming and scanning technique, we would find that before going into details about how engineers can learn from dance, the author first briefly mentions ways of...

Cambridge IELTS 15 Reading Test 1 Answers

PASSAGE 1: NUTMEG – A VALUABLE SPICE QUESTIONS 1- 4: COMPLETE THE NOTES BELOW.CHOOSE ONE WORD ONLY FROM THE PASSAGE FOR EACH ANSWER.WRITE YOUR ANSWER IN BOXES 1-8 ON YOUR ANSWER SHEET. 1. Answer: oval Key words: leaves, shape Using the scanning skill, we can see that the first paragraph describes the characteristics of the tree in detail, including...

CAMBRIDGE IELTS 14 READING TEST 4 ANSWERS 

PASSAGE 1: THE SECRET OF STAYING YOUNG QUESTIONS 1-8: COMPLETE THE NOTES BELOW. 1. ANSWER: FOUR / 4 Explain– Key words: focused age groups, ants– In paragraph 3, it is stated that “Giraldo focused on ants at four age ranges”,so the answer must be “four/4”. 2. ANSWER: YOUNG Explain– Key words: how well, ants, looked after– The first sentence of...

CAMBRIDGE IELTS 14 READING TEST 3 ANSWERS

PASSAGE 1: THE CONCEPT OF INTELLIGENCE QUESTIONS 1-3: READING PASSAGE 1 HAS SIX PARAGRAPHS, A-F. 1. ANSWER: B Explain ·     Key words: non-scientists, assumptions, intelligence, influence, behavior ·    People‟s behavior towards others‟ intelligence is mentioned in the first sentence of paragraph B: “implicit theories of...

CAMBRIDGE IELTS 14 READING TEST 2 ANSWERS

Cambridge IELTS 14 is the latest IELTS exam preparation.https://draftsbook.com/ will help you to answer all questions in cambridge ielts 14 reading test 2 with detail explanations. PASSAGE 1: ALEXANDER HENDERSON (1831-1913) QUESTIONS 1-8: DO THE FOLLOWING STATEMENTS AGREE WITH THE INFORMATION GIVEN IN READING PASSAGE 1? 1. ANSWER: FALSE Explain Henderson rarely...

Cambridge IELTS 14 Reading Test 1 Answers

Cambridge IELTS 14 is the latest IELTS exam preparation.https://draftsbook.com/ will help you to answer all questions in cambridge ielts 14 reading test 1 with detail explanations. PASSAGE 1: THE IMPORTANCE OF CHILDREN’S PLAY QUESTIONS 1-8: COMPLETE THE NOTES BELOW. 1. ANSWER: CREATIVITY Explain building a “magical kingdom” may help develop … – Key words: magical...

Cambridge IELTS 13 Reading Test 4 Answers 

PASSAGE 1: CUTTY SARK: THE FASTEST SAILING SHIP OF ALL TIME QUESTIONS 1-8: DO THE FOLLOWING STATEMENTS AGREE WITH THE INFORMATION GIVEN IN READING PASSAGE 1? 1. CLIPPERS WERE ORIGINALLY INTENDED TO BE USED AS PASSENGER SHIPS Key words: clippers, originally, passengerAt the beginning of paragraph 2, we find the statement: “The fastest commercial sailing...