Home > OS >  why to make a classes or attributes private?
why to make a classes or attributes private?

Time:04-19

I would like to ask why I should make a class private or make an attribute private I protect it from what? I think that only attributes that will be available to users in the application to supply them or update them like (mail, password, or age) only should be private but any other attribute that he wouldn't asked to fill out could be public? Is it true?

public class student{
    private String mail;
    public String getMail() {return mail;}
    public mail(String email) {mail=email;}
}

CodePudding user response:

Generally, in any OOP-Supported language, the encapsulation is used to prevent the alteration of code (data) accidentally from the outside functions. By defining the class members' private, we can protect the data from accidental corruption.

The following are the benefits of encapsulation:

  • Protection of data from accidental corruption
  • Specification of the accessibility of each of the members of a class to the code outside the class
  • Flexibility and extensibility of the code and reduction in complexity
  • Lower coupling between objects and hence improvement in code maintainability

Although we can and should use it in all scales of applications that we are writing, it's not about small applications. It's about large-scale frameworks.

I personally believe you can get so much benefit by deep diving into the OOP concepts. I can specify some references, yet there are plenty of exciting topics to follow by googling OOP.

Stackoverflow: Encapsulation concept

Object-Oriented programming (C#)

w3Schools What is OOP?

You also can search YouTube, there are plenty of resources to get started with the OOP Concept.

  • Related