Encapsulation and Subclassing is one of the most important, but also least understood, concepts in Java. Subclasses and encapsulation are different from inheritance, they are not simply about extending or overriding methods, but rather about ensuring that a class is allowing the functionality of another class to be used inside it.

The word sub-classing means to take an existing class and extend it so that you can create your own sub-classes that all inherit from the original class. This allows us to create our own classes that inherit from the original class.

The topic of this article is encapsulation and inheritance, two common programming concepts that can help you to write better code. This tutorial is for beginners with basic knowledge of Java. If you are a beginner and looking for a deeper understanding of encapsulation and inheritance, please refer to the list of recommended resources at the end of this article.

Encapsulation

Encapsulation is one of the four fundamental concepts of object-oriented programming. The other three are inheritance, polymorphism and abstraction. The term encapsulate means to encapsulate something or wrap it around an object to cover it. Encapsulation encapsulates the internal workings of a Java object. – The variables or data fields are hidden from the user of the object. – Methods, in Java functions, provide an explicit service to the user of the object, but hide the implementation. – As long as the services do not change, the implementation can be changed without affecting the user. An analogy for encapsulation is the steering wheel of a car. If you drive a car, whether it’s your car, a friend’s car, or a rental car, you’ve probably never thought about how the steering wheel performs the right or left turn function. The steering wheel can be connected to the front wheels in various ways: Ball, rack and pinion or an exotic set of servomechanisms. As long as the vehicle is steered correctly when you turn the wheel, the necessary functions are encapsulated in the wheel – you don’t have to think about implementing them.

Encapsulation: Example

What data and operations would you encapsulate in an employee object?

Single model

Suppose you are asked to make a model of a typical employee. What data might you provide in an object describing an employee?

  • Employee ID : You can use it as a unique identifier for employees.
  • Name: Humanizing an employee is always a good idea.
  • Citizen service number : Only US employees. For employees who do not work in the United States, you may need a different form of ID.
  • Salary: It is always a good idea to keep track of an employee’s salary.

What operations can you allow on the object worker?

  • Change the name: When an employee marries or divorces, there may be a name change.
  • Wage increases : It increases according to merit.

After creating an employee object, you probably don’t want to allow changes to the Employee ID or Social Security fields. So you need a way to create an employee without making changes, without using the allowed methods.

Encapsulation: Public and private access modifiers

In Java, there are three visibility modifiers: public, private and protected. – The public keyword applied to fields and methods allows any class in any package to access a field or method. – The keyword private, applied to fields and methods, allows access only to other methods of the class itself. Employee emp=new employee(); emp.salary=2000; //Compilation error – salary is a private field emp.raiseSalary(2000); //ok – The keyword private can also be applied to a method to hide implementation details.

Encapsulation: Private data, public methods

In Java, we achieve encapsulation using visibility modifiers. Declaring Java fields as private makes them invisible outside the methods of the class itself. In this example the fields custID, name and amount are now marked private and thus invisible outside the methods of the class itself. – The Employee class currently uses public access for all its fields. – To encapsulate the data, make the fields private. public class Employee { private int empId ; private String name ; private String ssn ; private double salary ; //… Constructor and methods }

Refined employee classification

The setting methods available in the class allow any class that uses an employee instance to modify the object’s ID, Salary, and SSN fields. From a business perspective, these are not the processes you want to see in an employee. Once an employee is created, these fields must be immutable (no change is allowed). 1 public class Employee { 2 // private fields … 3 public Employee () { 4 } 5 // Clear all other parameters 6 public void changeName(String newName) { 7 if (newName != null) { 8 this.name = newName; 9 } 10 } 11 12 public void raiseSalary(double increase) { 13 this.salary += increase; 14 } 15 } The Employee template from the previous section had only two operations: one to change an employee’s name (due to marriage or divorce) and one to increase an employee’s salary. To improve the Employee class, the first step is to remove the setup methods and create methods that clearly define their purpose. There are two methods here, one to change the name of the employee (setName) and the other to increase the salary of the employee (raiseSalary). Note that the implementation of the setName method checks the passed string parameter to ensure that the string is not null. The method may perform an additional test if necessary.

Make classes as immutable as possible

Good practice Immutability

Finally, since the class no longer has any setter methods, you need to find a way to set the initial value of the fields. The answer is to pass the value of each field when building the object. By creating a constructor that takes all fields as arguments, you can ensure that the employee instance is completely filled with data before it becomes a valid employee object. This constructor overrides the default constructor. Of course, the user can pass null values to your class, and you need to specify whether you want to validate them in the constructor. Strategies for dealing with such situations will be discussed in the following lessons. Removing the setting methods and replacing the No-Arg constructor also ensures that the Employee instance has immutable fields for the employee ID and Social Security Number (SSN). 1 public class Employee { 2 // private fields … 3 // Create an employee object 4 public Employee (int empId, String name, 5 String ssn, double salary) { 6 this.empId = empId; 7 this.name = name; 8 this.ssn = ssn; 9 this.salary = salary; 10 } 11 12 public void changeName(String newName) { . } 13 14 public void raiseSalary(double increase) { . } 15 }

Method name: Best practice

Selection of significant methods

Just as fields must uniquely define the type of data they store, methods must uniquely define the operations they perform. One of the easiest ways to improve the readability of your code (Java or otherwise) is to write method names that clearly define what they do. Although the fields are now hidden by using private access, the current Employee class has some problems. – The Setter methods (currently publicly available) allow any other class to change the ID, SSN and salary (up or down). – The current class does not really represent the operations defined in the original design of the worker class. – Two good practices for methods :

  • Hide as many implementation details as possible.
  • Name the method so that its use or functionality is clearly defined.

– In the original model of the Employee class, there were the operations Change Name and Increase Salary.

Encapsulation: Benefits

The advantages of using encapsulation are as follows:

  • Protects the system from unwanted client access.
  • Prevents clients from assigning unwanted values to their variables, which can make the object’s state unstable.
  • Allows you to change the implementation of the class without changing the client interface.

Create subclasses

You have created a Java class to model employee data and operations. Now suppose you want to specialize the data and operations to describe the handler. 1 package com.example.domain; 2 public class Manager { 3 private int empId; 4 private String name; 5 private String ssn; 6 private double salary; 7 private String deptName; 8 public Manager () { } 9 // Access methods and mutator. 10 }

Specialisation using Javasub-classification

The Manager class proposed here is very similar to the Employee class, but with some specializations. The manager also has a department with a department name. Therefore, additional surgeries are likely to take place. This suggests that a manager is an employee, but an employee with additional skills. However, if we defined Java classes this way, there would be a lot of redundant coding.

Subclass

In an object-oriented language like Java, subclassing is used to define a new class based on an existing class.

Simple Java program

When an existing class is a subclass, the newly created class is said to inherit the properties of another class. This new class is called a subclass and is a specialization of the superclass. All non-private fields and methods of the superclass are part of the subclass. Super class: Employees (upper class) In this diagram, the Manager class gets all the non-private fields and all the public methods of Employee. It is important to understand that a manager who specializes in employees is still an employee. Message: The term subclass is a bit misleading. Most people think the prefix sub means less. However, a Java subclass is the sum of itself and its parent class. When you create an instance of a subclass, the resulting structure in memory contains all the code of the parent class, a predecessor of the class, and so on down the class hierarchy to the object class.

Subclass Manager

The following piece of code illustrates the Java syntax for creating subclasses. The extends keyword creates an inheritance relationship: public class Manager extends Employee { } The following piece of code illustrates the inheritance relationships between the Manager class and its parent class, the Employee class. – The Manager class, which extends the Employee class, inherits all non-privatized data fields and methods from the latter. – Since Manager is also an employee, it follows that Manager has all the same attributes and operations as Employee. Message: The class Manager declares its own constructor. Constructors are not inherited from the parent class. For more information, see the next slide.

Designers in subclasses

Each subclass inherits the non-privatized fields and methods of its parent class (superclass). However, a subclass does not inherit a constructor from its parent class. He must provide a builder. The Java language specification contains the following description: Manufacturer’s statements are not members. They are never inherited and therefore cannot be hidden or redefined. Although the subclass inherits all methods and fields of the parent class, it does not inherit constructors. There are two ways to get a builder:

  • Write your own designer.
  • Use the default constructor.
    • If you do not declare a constructor, a default constructor with no arguments is provided.
    • If you declare your own builder, the default builder is no longer available.

Use of Super

To create an instance of a subclass, it is often easier to call the constructor of the parent class. – In his builder, Manager invokes the Employee builder. – The super keyword is used to call the constructor of the parent object. – This should be the designer’s first statement. – If not specified, the call to super() will be inserted for you by default. – The super keyword can also be used to invoke a parent method or to access a parent (non-private) field. super (empId, name, ssn, salary) ;

Director of Object Construction

Although the Manager.java file does not (explicitly) contain all the methods of the Employee.java class, they are included in the object definition. So, after creating an instance of the Manager object, you can use the methods declared in Employee. You can also call special methods of the Manager class. – Creating a Manager object is similar to creating an Employee object: Manager mgr = new Manager (102, Barbara Jones, 107-99-9078, 109345.67, Marketing); – All employee methods are available to managers: mgr.raiseSalary(10000,00) ; – The Manager class defines a new method to retrieve the department name: String dept = mgr.getDeptName() ;

Overload method

You may want to use methods with the same purpose (method name), such as B. print, expand to print different types. You can develop a method for each type: printInt(int i) printFloat(float f) printString(String s) But that would be tedious and not very object-oriented. Instead, you can create a reusable method name and just change the argument list. This process is called overloading. When overloading methods, the argument lists must differ in order, number, or type. And the types of yields can be different. However, two methods with the same argument list that differ only in the return type are unacceptable. Two rules apply to overloaded methods:

  • The argument lists should be different.
  • The types of return can be different.

Therefore, the following is not legal: public void print (int i) public String print (int i)

Overloaded manufacturers

Besides overloading methods, you can also overload constructors. The overloaded constructor is called based on the given parameters when new is executed.

Overburdened builders Example

The following example illustrates overloaded constructors: There are three overloaded constructors, which differ according to the number of arguments. public class Box { private double length, width, height ; public Box() { this.length = 1; this.height = 1; this.width = 1; } public Box(double length) { this.width = this.length = this.height = length ; } public Box(double length, double width, double height) { this.length = length; this.height = height; this.width = width; System.out.println(and the height of + height + .); } double volume() { return width * height * length ; } }

Unified heritage

The Java programming language allows a class to extend only one other class. This is called the unique heritage.Encapsulation and subclassing are two of the most valuable tools you will have as a programmer. These two concepts are the difference between creating a code base that works and having a code base that breaks. Subclassing is a great way to reuse code, encapsulation is an important means of ensuring that your code is safe and doesn’t violate the rules of other classes, and that you can extend a class to meet your own needs.. Read more about encapsulation oop and let us know what you think.

encapsulation in javaabstraction in javainheritance in javapolymorphism in javaencapsulation in java exampleencapsulation in python,People also search for,Privacy settings,How Search works,Encapsula…,Polymorph…,Inheritance,Abstraction,See more,encapsulation in java with realtime example,encapsulation in java example,encapsulation in python,encapsulation oop,encapsulation in c++,difference between abstraction and encapsulation in java,encapsulation real time example,define encapsulation

You May Also Like

How to Use and Manage Clipboard History in Windows 10

Windows 10’s Cortana Voice Assistant is a handy tool. But it is…

How To Enable Google Docs Dark Mode

Google Apps are full of easter eggs. Most of them don’t change…

Steam Takes Forever To Open Complete Fix 2021

For Steam users, it takes forever to open and start the game…

🥇 Configure Telegram Bot  Step by Step Guide ▷ 2021

Telegram is a messaging service that allows you to create your own…