Java data encapsulation

Created By: chatGPT

Data encapsulation is a fundamental concept in object-oriented programming (OOP). It restricts direct access to some of an object's components, which can prevent the accidental modification of data. This is achieved by using access modifiers to set the visibility of class members. The idea is to bundle the data (attributes) and methods (functions) that operate on the data into a single unit, the class.
public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        } else {
            System.out.println("Age must be positive!");
        }
    }
}
In the code example, the Person class encapsulates the attributes name and age, making them private. This means they cannot be accessed directly from outside the class. Instead, we use getter and setter methods to safely access and modify these attributes. The setAge method includes a validation check to ensure that the age is a positive number, demonstrating how encapsulation can enforce constraints on the object's state.
public class Main {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("John");
        person.setAge(25);

        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());

        person.setAge(-5);  // This will trigger a warning
    }
}
By using data encapsulation, you achieve several benefits, such as increased maintainability, flexibility, and security of your code. It allows you to change the internal implementation of a class without affecting code that depends on the class, as long as the interface remains the same. This encourages better software design practices.
// Adjusting implementation without affecting external code
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        setAge(age);
    }

    // Other methods remain unchanged
}
Introduction And SetupVariablesData TypesIntFloatDoubleCharBooleanStringByteShortLongArrayListMethodVoidReturnParametersArgumentsControl FlowIf StatementElse StatementElse If StatementSwitch StatementCaseBreakContinueFor LoopWhile LoopDo While LoopEnhanced For LoopFunctionsStatic MethodInstance MethodConstructorOverloadingOverridingAccess ModifiersPrivateProtectedPackage PrivateOperatorsArithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsTernary OperatorInstanceof OperatorArrayListSetMapHashmapHashtableQueStackCommentsSingle Line CommentMulti Line CommentSyntaxSemicolonsCurly BracesParenthesesData EncapsulationInheritancePolymorphismAbstract ClassInterfaceException HandlingTry BlockCatch BlockFinally BlockThrowThrowsChecked ExceptionUnchecked ExceptionSyntax ErrorsRuntime ErrorsLogic ErrorsEvent HandlingListenersAction EventsMouse EventsKeyboard EventsWindow EventsFocus EventsKey ListenerMouse ListenerAction ListenerThreadingSynchronizationVolatile KeywordConcurrencyJava Memory Model