Friday, May 9, 2025
Alternative Way
  • Home
  • Latest
    • Latest
  • News
  • World Tech
  • World Gaming
  • Minecraft
  • Guides
  • Contact Us
  • About The Team
    • Privacy Policy
    • Terms of Use
No Result
View All Result
  • Home
  • Latest
    • Latest
  • News
  • World Tech
  • World Gaming
  • Minecraft
  • Guides
  • Contact Us
  • About The Team
    • Privacy Policy
    • Terms of Use
No Result
View All Result
Alternative Way
No Result
View All Result

Beginners Guide to Java Encapsulation and Subclassing – The Geek Diary

Gordon James by Gordon James
October 3, 2021
in World Tech Code
0 0
0
Home World Tech Code

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.

Table of Contents

Toggle
  • Encapsulation
  • Encapsulation: Example
    • Single model
  • Encapsulation: Public and private access modifiers
  • Encapsulation: Private data, public methods
  • Refined employee classification
  • Make classes as immutable as possible
    • Good practice Immutability
  • Method name: Best practice
    • Selection of significant methods
  • Encapsulation: Benefits
  • Create subclasses
    • Specialisation using Javasub-classification
  • Subclass
    • Simple Java program
  • Subclass Manager
  • Designers in subclasses
  • Use of Super
  • Director of Object Construction
  • Overload method
  • Overloaded manufacturers
    • Overburdened builders Example
  • Unified heritage
      • Related Tags:

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.

Related Tags:

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

Total
0
Shares
Share 0
Tweet 0
Pin it 0
Share 0
ShareTweet
Gordon James

Gordon James

Next Post

Abstract and Nested Classes – The Geek Diary

  • Trending
  • Comments
  • Latest
How To Get Free Internet On Android Without Service

How To Get Free Internet On Android Without Service

March 10, 2022
🥇 +4 Neo Geo Emulators for Android  List ▷ 2021

🥇 +4 Neo Geo Emulators for Android  List ▷ 2021

October 3, 2021

Fix: Notifications not working on Nova Launcher

October 3, 2021
How to Fix OpenVPN Connected but Not Changing IP Address

How to Fix OpenVPN Connected but Not Changing IP Address

October 3, 2021

Setting Up Directory Sync Between On-Premises Active Directory with Microsoft 365 Azure AD

0
🥇 DELETE ACCOUNT from PS4  ▷ Step by Step Guide ▷ 2020

🥇 DELETE ACCOUNT from PS4  ▷ Step by Step Guide ▷ 2020

0
🥇 PPTX File Extension  What is .Pptx and how to open them? ▷ 2020

🥇 PPTX File Extension  What is .Pptx and how to open them? ▷ 2020

0
🥇 Make a Crossword in Microsoft Word  Step by Step Guide ▷ 2020

🥇 Make a Crossword in Microsoft Word  Step by Step Guide ▷ 2020

0
What to Know About Car Shipping Services

What to Know About Car Shipping Services

May 7, 2025
CS2 Skins-Why Trade Them?

CS2 Skins-Why Trade Them?

May 7, 2025
Alternative Routes: Successfully Exiting Your Wyndham Timeshare Without The Stress

Alternative Routes: Successfully Exiting Your Wyndham Timeshare Without The Stress

May 6, 2025
The Ultimate Seiko Watch Gift Guide

The Ultimate Seiko Watch Gift Guide

May 1, 2025

There's always an alternative Way!
Find us at 4145 Zolynthian Street, Vylorthos, QP 78425
No Result
View All Result
  • Home
  • Latest
    • Latest
  • News
  • World Tech
  • World Gaming
  • Minecraft
  • Guides
  • Contact Us
  • About The Team
    • Privacy Policy
    • Terms of Use

© 2022 - Alternative Way

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
No Result
View All Result
  • Home
    • Home – Layout 1
    • Home – Layout 2
    • Home – Layout 3
    • Home – Layout 4
    • Home – Layout 5
  • Travel News

© 2025 JNews - Premium WordPress news & magazine theme by Jegtheme.