Object Model in Java
Have you ever thought about how software programs can see and communicate with the components that make them up?
The object model is useful in this situation. Developers can represent those components as objects using sophisticated object-oriented techniques thanks to a strong system or interface.
The object model is actually so crucial to software development that it’s frequently one of the first stages. The object model establishes the framework for a reliable, adaptable, and scalable application design by defining crucial features like inheritance and encapsulation. Are you set to learn more about object-oriented programming?
Objects and Classes
Java or any other Object-Oriented Programming Language’s Object-Oriented paradigm depends on objects and classes. Let’s examine them more closely to see what they are all about −
Object
In object-oriented programming, an object is comparable to a real-world element, whether physical or conceptual, with its distinct properties.
Here are some of the defining features of an object −
- Unique − Every object is distinct from all other objects in the system, with its own attributes and behaviors.
- State − Each object has a state that represents its current properties and values specific to that particular object.
- Behavior − An object’s behavior refers to the actions it can take and how it interacts with other objects, both internally and externally.
For example, a person could be represented as a physical object, while a process or a product might be better suited as a conceptual object.
Class
A class is a blueprint or model for an object that depicts a collection of objects with similar traits. These things are referred to as instances of the class. There are several elements in a class −
The information kept in an object’s attributes can vary from one object pertaining to the same class to another. Class data is the name given to these characteristics.
Operations are the procedures and techniques used to specify and depict these objects’ activities.
Think about the class «Employee,» for instance. The following characteristics could apply to this class −
- The employee’s experience
- The department in which the employee is working
- The year in which the student is the employee started working
- Personal information such as the employee’s name, employeel ID, and date of birth.
Using this class, you can carry out a number of operations, including −
- averageyears() − calculates the average years of employee experience.
- totalyears() − calculates the total years of experience of an employee.
Algorithm
- Step 1 − Create the «Employee» public class.
- Step 2 − Call the «total_years» function with the two numbers 2 and 4 to add the total number of employee experience.
- Step 3 − Then we have called another function called «avg_years» with the result from «total_years» and an integer 2. This function calculates the average of the two numbers. It returns the result as a decimal.
- Step 4 − The program prints the results to the console using the System.out.println method.
- Step 5 − The output displays the total number of years of experience, which is 6. The average of the two numbers is 3.0.
Example
The below code defines a class «Employee» that calculates the total and average years of experience for two employees and prints the results to the console.
import java.io.*; public class Employee < public static void main (String[] args) < // passing parameters to functions int tot = total_years(2,4); double avg = avg_years(tot, 2); // printing the output System.out.println("The total years is = "+tot+". The average is = "+avg+"."); >// function to calculate total public static int total_years(int executive, int senior) < int total = executive + senior; return total; >// function to calculate average years public static double avg_years(int total, int num_subs) < double avg = total/num_subs; return avg; >>
Output
The total years is = 6. The average is = 3.0.
Concepts of Encapsulation and Data Hiding
To ensure that our data is kept secure and not vulnerable to outside interference, encapsulation and data hiding are essential concepts that must be implemented.
Encapsulation involves grouping methods and attributes together in a class. External access to internal details or class attributes is only permitted if the class provides an interface for it.
Data hiding, on the other hand, is the process of safeguarding an object from direct access by external methods.
Many objects need to be able to communicate with one another in order to make an interactive application. This communication is facilitated by message passing, which entails calling class methods between objects created by various processes. In most cases, message passing is unidirectional and enables communication between two things.
Inheritance
It is possible to create new classes from existing classes that have wider functionality by using the fundamental concept of inheritance. The initial classes are commonly referred to as parent classes, base classes, or super-classes, whereas the new classes are known as child classes, derived classes, or subclasses.
Subclasses may inherit or acquire the characteristics and capabilities of their superclass as long as the superclass allows it.(es). Additionally, the child class has the power to modify any inherited super-class methods as well as introduce new traits and methods of its own.
Because inheritance establishes an «is-a» relationship between parent and child classes, it provides programmers with a powerful instrument for developing object-oriented applications.
For instance, you may create classes, like Crocodile, Snake, and Chameleon, using the Reptile class as a blueprint. Apart from the common features of being a reptile, each has distinctive characteristics. It is, therefore true to say that a crocodile «is-a» a reptile.
Polymorphism
The word «polymorphism,» which derives from Greek, refers to the capacity to assume several shapes. It refers to the capacity of operations to act differently based on the type of object they are applied to in the context of object-oriented programming.
This makes it especially helpful in inheritance because it enables objects with various internal structures to share a common interface.
Let’s use the two classes Triangle and Rectangle as an illustration. Both classes include a method called findArea().
Although the method’s name and objective are the same in both classes, how it is internally implemented (i.e., how the area is calculated) varies depending on the class.
When an object of class Rectangle runs its findArea() function, it does so without interfering with the findArea() method of the Triangle class in calculating the area of the circle.
Generalization and Specialization
In a class hierarchy, subclasses inherit from superclasses, which is reflected in generalisation and specialisation.
In the generalisation process, subclasses are joined to form a generalized super-class, merging the shared traits of classes to generate a class at a higher level of the hierarchy.
It suggests a «is — a — kind of» relationship.
For instance, «bike is a kind of land vehicle» or «boat is a kind of water vehicle.»
The opposite of generalization is the process of specialization. In this instance, specialized classes are made from pre-existing classes using the identifying traits of groups of items. You can think of subclasses as specialized versions of the superclass.
Links and Associations
Links and associations are used to represent relationships between objects. A link represents a connection between objects through which they collaborate. An association is a group of links with common structure and behavior, representing relationships between objects of one or more classes.
The degree of association indicates the number of classes that are linked.
Cardinality ratios of associations denote the number of instances participating in an association.
Aggregation and Composition
Aggregation or composition is a relationship among classes where a class can be made up of any combination of objects of other classes.
Objects can now be placed immediately within the body of other classes.
Aggregation is referred to as a «part-of» or «has-a» relationship, with the ability to navigate from the whole to its parts. An aggregate entity is made up of one or more other objects.
Conclusion
Since it enables developers to represent components as objects using object-oriented techniques, the object model is a crucial part of software development. Through objects and classes, which form the basis of the Object-Oriented Paradigm, Java uses the object model. Key ideas within the object model that improve the adaptability, scalability, and robustness of applications include encapsulation, data hiding, inheritance, and polymorphism. By grasping these ideas, developers can come up with more effective, efficient, and versatile software apps.
Object modelling in java
The term Model Object is an informal term, with no widely accepted definition. Here, Model Objects (MOs) refer to data-centric classes which encapsulate closely related items.
- are very common, and are used in almost all applications
- are often central to an application, since they usually model problem domain objects
- often map roughly to the records of a corresponding database table
- are often used as return values for Data Access Object methods
- are easily tested using JUnit (or a similar tool)
- can be used to implement the Model in a Model-View-Controller pattern
Not necessarily. In fact, some argue that the JavaBeans style is to be avoided as a general model for Model Objects.
Should Model Objects be immutable?
Given the deep simplicity of immutable objects, some prefer to design their Model Objects as immutable. However, when the underlying data changes, a new object must be created, instead of simply calling a setXXX method on an existing object. Some argue that this penalty is too high, while others argue that it is a micro-optimization — especially in cases where the data is «read-mostly», and the state of corresponding Model Objects changes only rarely.
Implementing Model Objects as immutable seems particularly natural in web applications. There, Model Objects are most commonly placed in request scope, not session scope. In this case, there is no long-lived object for the user to directly alter, so the Model Object can be immutable.
Comment represents a comment posted to a message board. Its implementation follows the Immutable Object pattern. Comment provides the usual getXXX methods. Note that, in this case, a defensive copy is used for the Date field. It also implements the toString , equals , and hashCode methods.
The constructor is responsible for establishing the class invariant, and performs Model Object validation.
package hirondelle.fish.main.discussion; import java.util.*; import hirondelle.web4j.model.ModelCtorException; import hirondelle.web4j.model.ModelUtil; import hirondelle.web4j.model.Check; import hirondelle.web4j.security.SafeText; import static hirondelle.web4j.util.Consts.FAILS; /** Comment posted by a possibly-anonymous user. */ public final class Comment < /** Constructor. @param aUserName identifies the logged in user posting the comment. @param aBody the comment, must have content. @param aDate date and time when the message was posted. */ public Comment ( SafeText aUserName, SafeText aBody, Date aDate ) throws ModelCtorException < fUserName = aUserName; fBody = aBody; fDate = aDate.getTime(); validateState(); >/** Return the logged in user name passed to the constructor. */ public SafeText getUserName() < return fUserName; > /** Return the body of the message passed to the constructor. */ public SafeText getBody() < return fBody; > /** Return a defensive copy of the date passed to the constructor. The caller may change the state of the returned value, without affecting the internals of this Comment. Such copying is needed since a is a mutable object. */ public Date getDate() < // the returned object is independent of fDate return new Date(fDate); > /** Intended for debugging only. */ @Override public String toString() < return ModelUtil.toStringFor(this); > @Override public boolean equals( Object aThat ) < Boolean result = ModelUtil.quickEquals(this, aThat); if ( result == null )< Comment that = (Comment) aThat; result = ModelUtil.equalsFor( this.getSignificantFields(), that.getSignificantFields() ); > return result; > @Override public int hashCode() < if ( fHashCode == 0 ) < fHashCode = ModelUtil.hashCodeFor(getSignificantFields()); >return fHashCode; > // PRIVATE // private final SafeText fUserName; private final SafeText fBody; /** Long is used here instead of Date in order to ensure immutability.*/ private final long fDate; private int fHashCode; private Object[] getSignificantFields()< return new Object[] new Date(fDate)>; > private void validateState() throws ModelCtorException < ModelCtorException ex = new ModelCtorException(); if( FAILS == Check.required(fUserName) ) < ex.add("User name must have content."); > if ( FAILS == Check.required(fBody) ) < ex.add("Comment body must have content."); > if ( ! ex.isEmpty() ) throw ex; > >
Java Practices 3.012
© 2023 John O’Hanley
Source Code | Contact | License | RSS
Individual code snippets have a BSD license
Over 1,000,000 unique IPs last year
Last updated 2023-01-03
— In Memoriam : Bill Dirani —