Showing posts with label java OOPS. Show all posts
Showing posts with label java OOPS. Show all posts

Friday, March 1, 2024

JAVA OOPS

 JAVA OOPS


  • ADVANTAGES AND DISADVANTAGES 
  • BEST PRACTICES IN JAVA OOPS CONCEPT 
  • CONCEPTS IN OOPS
  • WHY JAVA IS NOT PURELY OBJECT ORIENTED PROGRAMMING

Programming languages that largely rely on objects to carry out the logic provided in their source code are referred to as object-oriented programming languages, or OOPs. From the perspective of the user or observer, objects perform the roles assigned to them. Object-oriented programming eyes to use real-world programming constructs such as inheritance, hiding, polymorphism, etc. To guarantee a close relationship between data and the functions that handle it, object-oriented programming (OOP) was developed. This data is accessible to other parts of the code in addition to the problematic function.

Compared to procedural programming, object-oriented programming has the following advantages:

OOP is slower and more difficult to execute than OOP.

Innovative thinking provides programs with a strong foundation.

Object-oriented programming (OOP) promotes the "Don't repeat yourself" idea, which makes it easier to maintain, edit, and debug Java code.

Object-oriented programming (OOP) facilitates the completion of the building of reusable applications by minimizing code and development time.

Suggestion: Follow the "Don't Repeat Yourself" guideline to lessen the quantity of repetitive code. Instead of repeating the application-wide code, it would be more effective to gather it into one place and then utilize it again.

Advantages and disadvantages of oops in Java

Advantages:

If object-oriented programming in Java is new to you, you should learn about all of its advantages:

Reusability

Reusable code is defined as code that is written just once but is used again. As long as it is classified, a particular piece of code can be used as much as necessary.

Data Redundancy

One of the key advantages of Java OOP concepts is data redundancy. The same data may be produced in a data warehouse by storing it in two different places. By building on preexisting class definitions, you may use similar functions in other classes and create common class definitions.

Code Maintenance

The concept behind Java OOPs is to make it easier to maintain current code by allowing new objects to be formed with just little modifications from old ones. It enables users to continuously update and change outdated applications.

Security

Java OOP concepts like data hiding and abstraction provide limited discovery filtering. As a consequence, OOP functions only display the data that is necessary for security.

Benefits of Design

Java OOPs provide designers more creative flexibility. This leads to better models. The program eventually reaches its critical limits. It's now easy to program each non-operation separately.

Easy Debugging

The Java OOPs concept enables the use of self-contained encapsulation objects. Thus, engineers can promptly fix problems that keep coming up. Furthermore, the OOP features prevent the creation of duplicate code.

Disadvantage:

Performance

Because Java needs to be interpreted at runtime, it is slower than languages like C and C++. All operating systems are compatible with it, though. Conversely, C++ applications execute more quickly since they are built directly into binary format for every operating system.

Memory consumption

Java programs need more memory when they are running in a Java virtual machine.

Price

Java is a somewhat expensive programming language because it needs more processing power and also has high memory requirements. More reliable hardware is needed for the Java program to run.

Less machine interaction

Java is not a good fit for applications that need to run quickly and interact directly with the hardware because of its difficulty in doing so and its lack of explicit references.

Garbage Collection

Java features automatic trash collection, over which the developer has no control. It is devoid of memory-freeing functions like delete() and free().

Best Practices in Java OOP Concepts

The Java OOP paradigm aims to save time without compromising security or usability. You can get there by adhering to these object-oriented programming guidelines:

The Java philosophy of "Don't Repeat Yourself," or SEKA, is fundamental. Therefore, it's not a good idea to utilize the same code again. Try not to use more than one strategy in any one of your apps.

The first step in making your Java code future-proof is to encapsulate it by designating all methods and variables as private. As appropriate, access to "protected" can be progressively expanded. But do keep it a secret.

One of the best practices for Java object-oriented programming is to use single responsibility. In particular, you must confirm that the class has just one function. Consequently, the class may be extended for use in various settings or used independently. This helps to detangle several processes.

The open-closed design pattern is one of the best ways to implement the Java OOP concept. The classes and methods must remain open to add extensions, but they must be closed to edit. We can be confident that the tried-and-true Java OOP implementation will remain unchanged in this way. But they might also be modified to do different functions.

Let's go over the prerequisites, which involve declaring methods and passing messages before we get started. It has six parts, which start with the description of the method:

Access Modifier: describes the context in which the method can be called, or the access type of the method. There are 4 main types of access definitions in Java: This is public information that is accessible to all classes in your application.

"Protected" denotes that its access is restricted to the package that contains its definition and any subclasses that are listed inside. You can only access this property within the class that specifies it.

Proven in the identical class and package as its definition: default (defined/declared in an unmodified manner).

The method's value, or void if the function returns null, is to the left of the return type.

Procedure identifier: The guidelines for field names are the same as those for method names, notwithstanding the modest differences in procedure.

In a parameter list, which is divided by commas, input parameters are defined in parenthesis before their data type. If there are no arguments given, use empty parentheses. List of exclusions: Exceptions are expected by this function. You can define these exclusions.

You must run the code block included in parentheses, or the method body, to accomplish the intended result.

Message passing: The sending and receiving of messages allows objects to share data. Since the message is an instruction to do an action, calling an action on the receiving object produces the expected results. Objects’ names, functions’ names, and the definition of the information are all contained in a message.

After discussing the fundamentals, let's examine the four pillars of object-oriented programming (OOP). That being said, let's start by being acquainted with the features of an OO language.

The concepts of OOPS are:

1)      Class

2)      Object

3)      Method and method passing

4)      Abstraction

5)      Encapsulation

6)      Inheritance

7)      Polymorphism

 

Class

A class is a collection of objects. That is a logical entity.

It may also be viewed as a template that can be utilized to create a single object. There isn't a specific location needed for the class.

In class declarations, the following components are typically present in the following order:

* Adjectives Further details on establishing default permissions or making the class public may be found here.

Modifiers: As per custom, the class name needs to start with a capital letter and be appropriately capitalized. Potential superclass: A keyword is extended if the class name includes both the keyword and its superclass. A class cannot have more than one superclass as a descendant.

A list of all interfaces that the class implements, separated by commas and preceded by the word implements, should be included in the elements section. A single class can implement many user interfaces.

The class body, {}, is enclosed in braces {}.

Object

Any entities that can be described by their states and actions are considered objects. Items such as a table, chair, laptop, bike, pen, etc. It might be physical or logical.

Objects can be defined using class instances. An item has two properties: an address and a memory location. For objects to communicate, it is not required for them to know one other's data or code. All that has to be done is provide the message type and the response object type.

A dog is an excellent illustration of an item with characteristics like the dog’s color and its breed as well as actions like waving its hand. the tail, squealing, eating, and so on.

To begin testing out the class and object methods, let's build an application in Java:


Now we will discuss the most important pillars of the OOPS concept

1 Abstraction

The user only sees the information pertinent to their requirements when using data abstraction. Units that are unnecessary or inconsequential are not shown to the user. For example, a vehicle is defined as a car, not as a group of pieces.

Data abstraction may also be thought of as a means of separating away any unnecessary information from an object's required attributes. A thing's characteristics and behaviors, which also distinguish it from other things of its sort, can be used to classify and organize it.

See a real-world example of how to operate a car. The driver just understands that applying the brakes and pressing the gas pedal are controls; he has no understanding of what makes the automobile go faster or slower. He's not familiar with the location of the accelerator, brakes, or other controls on the automobile, nor with its internal workings. It isn't specific enough.

Java allows abstraction to be achieved through the use of abstract classes and user interfaces. We can use interfaces to achieve complete abstraction.

An abstract method lacks an implementation and only contains the specification of the method.

Introduction to an abstract class.

Encapsulation

The definition is putting information together into a single unit. It serves as a connection between the data and the code it processes. Another way to imagine encapsulation is as a barrier that keeps programs from accessing data that isn't inside its borders of protection.

Technically speaking, encapsulation means that only the member functions of a class have access to its variables and data; other classes cannot view them. Similar to data concealing, encapsulation prevents other classes from accessing the data of one class. In this sense, "encapsulation" and "data hiding" are synonymous.

Encapsulation may be implemented by a class by declaring public methods to access and set the values of all of its private variables.

Introduction Encapsulation.


Inheritance

Inheritance is one of the fundamental features of object-oriented programming, or OOP. The Java programming language has an attribute called inheritance that allows one class to utilize the fields and functions of another. The inheritance process is carried out via the extends keyword. Inheritance is one term for a "is-a" relationship.

Here are some terms that we should review that are frequently used:

A class that has its properties passed down across generations of classes is also called a superclass, root class, or inheritable class.

Classes that inherit from another type are among the many various sorts of classes that might be referred to as "subclasses." In addition to adding some of its own, a subclass can inherit the attributes and methods of its parent class.

Inheritance supports the concept of "reusability" by enabling us to create new classes when there are already existing ones, from which we may derive our own class, which already has part of the functionality we want. By doing this, we may once more utilize the fields and functionalities of an existing class.

Introduction to inheritance.

Polymorphism

Variations in an organism's ability to perform a certain function are referred to as polymorphism in biology. Create a shape (rectangle, square, etc.) or convince the client to reconsider.

Polymorphism can be achieved in Java using method overloading and overriding.

Speaking is another thing that springs to mind. A dog could bark and a cat might meow, for example.

Let us understand polymorphism in a Java program 


 

Few more concepts related to oops 
Coupling
"Relation" refers to a distinct class or dependence on information or knowledge. When classes are 
mutually aware, this happens. When one class knows another class, there is a strong relationship 
between them. The modifiers private, protected, and public can be used in Java to specify the 
visibility of a class, method, and field. Interfaces can be utilized for looser coupling as they don't have 
a setup.
Cohesion
Cohesion is defined as the ability of a component to perform a single, designated function with 
effectiveness. There is a pretty consistent way to complete a single task. We use the weakly connected
 technique to divide the task into smaller, more manageable portions. The input/output classes, 
interface, and other elements of the java.io package make it incredibly well-structured. In contrast, 
the java. util package only has a weak connection because it contains different and unrelated classes 
and interfaces.
Association
A relationship shows the relationship that exists between two or more elements. In this 
scenario, one item can be linked to an arbitrary number of other objects. There are four 
types of associations that objects can have:
One-to-one
One-to-many
Many-to-one and
Many-to-many
Here are some actual cases that assist us in understanding the connection. A nation with one prime
minister and several ministries answering to him or her is an example of a one-to-many relationship.
Additionally, a prime minister can have many ministries, many ministers, and many members of
parliament with one prime minister (many-to-one). You can establish a two-way or one-way connection.
Merging
The whole point of merging is to combine. Aggregation represents the connection in which one item 
incorporates other objects into its state. The relationships between the items it shows are only 
shaky at best. In Java, this is also known as the has connection. Take inheritance as an example to 
demonstrate the is-relationship. This is an additional technique for material reuse.
Composition
Arranging is another type of combination. A composition is an entity that, in its condition, consists of other 
things. The contained object and the dependent item are closely connected. This is the circumstance in which 
the things mentioned therein do not exist on their own. All of a parent object's offspring will be deleted along 
with it.
 

Why java is not purely object-oriented programming?

A programming language is referred to as pure or complete object-oriented if it supports or has functions that treat each component of a program as an object. Basic data types like int, char, float, bool, etc. are incompatible with it.

They are:

Data Encapsulation/Hiding-Inheritance

Polymorphism

Abstraction

All predefined types are objects

All user-defined types are objects

All operations on objects must be performed only by methods visible on objects.

Example: Smalltalk \ n

Java does not support functions 5 or 7, however, it does support functions 1, 2, 3, 4, and 6. Due to these characteristics, Java is more than just an object-oriented language:

Simple data types as objects include char, bool, float, int, and long. Smalltalk is an object-oriented language that is "pure" compared to Java and C++ since it does not differentiate between object values and primitive type values. Even the most fundamental data types in Smalltalk—characters, Booleans, and integers—are objects. Java has a collection of predefined kinds known as basic types in addition to objects.

Int a= 5;

System.out.print(A);

Static keyword: When a class is marked as static, using a Java object is not required. A static function or variable's object-oriented attribute cannot be overridden by invoking it with a dot (.) or a class object. Class of application: A wrapper class makes it feasible to convert an object from a primitive and vice versa. primitive Java lets you use int, float, etc. instead of using integer and float. To interact with an object, you don't always need to call its methods. while utilizing mathematical operations, for example.

String s1 = “ABC” + “A”;

Even with Wrapper classes, Java is not a true OOP language since it depends on built-in capabilities like Unboxing and Autoboxing. When you construct an integer rather than an int and then do math operations on it, Java will revert to utilizing the old-fashioned int type.

STRING IN JAVA

 Strings in Java 

  • WHAT IS STRING
  • WAYS OF CREATING A STRING
  • INTERFACES AND CLASSES IN STRINGS IN JAVA 
  • JAVA STRING CLASS METHODS 
  • STRING TOKENIZER
  • IMMUTABLE STRING IN JAVA 
  • MEMORY ALLOTMENT IN STRING 

In this example, object creation is restricted to a single instance. It will first create a new string object because the "Welcome" object isn't already in the JVM's collection of string constants. Then, instead of creating a new object, it finds the collection whose string value is "Welcome" and returns a reference to the instance that already exists. This article covers the capabilities of strings in the Java language.

What are strings in Java?

Java's "string" object type may store character values; each character should be represented by 16 bits, according to the Unicode Technical Report (UTF). Similar to any other string in Java.

String s =” India”;

The Java String class contains countless methods for interacting with strings, such as compare, concat, equals, split, length, replace, compareTo, intern, and substring. This project is for Java. lang.

The String class implements the methods Serializable, Comparable, and CharSequence.

Example of using a string












Example

    Java strings are immutable, meaning they cannot be changed. Every time a string is changed, a new instance is created. You may use strings that can be changed with the StringBuilder and String Buffer classes.

    We shall discuss immutable strings later. We'll start by going over the fundamentals of strings and how to create a string object in Java.

    Ways of creating a string

    There are two ways of creating a string

    1)      by string literal

    2)      by new keyword

    By string literal

    For the sake of Java's memory efficiency (because the set string constant stops duplicate objects from being created).

    Ex: string demo string = “India”;

    By using keyword

    for example: String s=new String("Welcome");

    Here, the Java Virtual Machine (JVM) creates a new String object in traditional (non-pooled) heap memory and appends the literal "Welcome" to the String constant. The variables designate items that are on the heap (and those that are not).

    For example:




















Interfaces and classes in Strings in Java

The Char Buffer class is an example of an interface that is implemented by other classes. You may utilize character buffers instead of Char-Sequences with this class. To see this in action, go no further than the java. util.regex package, which contains regular expressions.

A string is presented here. Once created, string objects in Java cannot be edited; this is known as immutability.

Char-Sequence Interface

The Char-Sequence interface is used to represent strings in Java.

The following classes meet the requirements of the Char-Sequence interface. You may take use of their many helpful characteristics, such as substring, last occurrence, first occurrence, chaining, vertical, horizontal, and many more.

  • String
  • StringBuffer
  • StringBuilder

 

1)      String

The string class is said to as immutable as it is a constant that cannot be changed once it is formed. Every update necessitates the creation of a new object, and even its own operations—like to upper and to lower—return new objects that are identical to the original. It is by default thread-safe.

Syntax:

    String str= "LMS";

           or
String str= new String("LMS")

 

2)      String buffer

StringBuffer is an analog class for Strings that provides a large portion of Strings' functionality. Instead of using a string, which has a fixed length and cannot be altered, you may use the ThreadSafe class StringBuffer if you need to use a shared string buffer object while working in a multithreaded environment. Due to its overhead, which comes from being thread-safe, its primary use is in multi-threaded systems.

Syntax

                  StringBuffer demoString = new StringBuffer("LMS");
 

       3) String builder

Java's StringBuilder class represents a changing string. The StringBuilder class is a suitable substitute for Java's String class, which creates an immutable string. Although it is thread-specific rather than thread-safe, overload is avoided. For the above-mentioned reasons, it is mostly used in programs that do not support threads.

Syntax:

StringBuilder demoString = new StringBuilder();
 

demoString.append("LMS"); 

Java string class methods
The java.lang.String class provides many useful methods for performing operations on an array of character values..



























 











String tokenizer

The String-Tokenizer object internally maintains track of the string's current position. Some techniques move the pointer past the characters after they have been processed. The token may be acquired by extracting a substring from the string that was used to create the String-Tokenizer object. To create strings with optional prefixes and suffixes at the beginning and end, separated by a delimiter, one handy Java class is StringJoiner. Instead of writing a ton of code to do the same task as appending a delimiter to each string using the StringBuilder class, String-Joiner provides an easy-to-use solution.

Syntax: public StringJoiner (CharSequence delimiter)

Here, the JVM checks the string against the standard store. If there's not already a string in the pool, a new string instance is created and added. If there isn't already a string instance in the pool, one is created and added. If the string already exists, the constructor won't be called. Instead, it goes back to using the same instance as before. The cache that contains all of these strings is sometimes referred to as the "String Pool" or "String Constant pool." Up until JDK 6, the String collection in previous versions of Java was in PermGen (permanent generation) mode. It was instead moved to the main heap due to a change in JDK 7.

Immutable string in Java

In Java, string objects cannot be changed. Immaculate, to put it simply, means unchanged. A new string object must be generated since an existing string object cannot have its contents or status changed.

Let us understand with a program:














Here, Sachin is still Sachin in this instance, but "Sachin Tendulkar" is added to an already-existing object. For this reason, the string is called immutable.

As can be seen in the attached image, even though two objects are formed, "Sachin" rather than "Sachin Tendulkar" is used in the reference variable. On the other hand, when we explicitly add the object "Sachin Tendulkar" to the reference variable, it gets referred.











Memory allotment on string

When a string object is created literally, it is added to a collection of string constants. As a result, the JVM could optimize how string literals are initialized.

Syntax: string demostring = “LMS”

Another technique to define strings is to use the new operator to dynamically allocate them. When dynamic allocation is done, a string is given a new heap position. This string is not obtained via the string constant set.

Syntax: string demo string = new string(“LMS”)

For example:















Why did the String pool move from Perm-Gen to the normal heap area?

PermGen has a 64 MB default size, which limits its storage capacity. The issue was brought on by the creation and storage of an excessive number of string objects in PermGen space. As a result, the String pool was moved to a larger stack area. Using the concept of a string literal, Java memory management is made more effective.

Whether or whether the exact same object already exists in the string pool, the Java Virtual Machine will create a new string object on the usual stack region when you use the "new" keyword.

Example: String demoString = new String("Bhubaneswar");















Few more examples



Featured Post

ASSOCIATION RULE IN MACHINE LEARNING/PYTHON/ARTIFICIAL INTELLIGENCE

Association rule   Rule Evaluation Metrics Applications of Association Rule Learning Advantages of Association Rule Mining Disadvantages of ...

Popular