Learn about fundamental object-oriented programming concepts in Java, including classes, objects, and access modifiers.
Classes are templates for creating objects. They define the structure and behavior that the objects will have.
Instance variables store the state of an object. Each object created from a class has its own copy of these variables.
public class Person { // Instance variables private String name; private int age; }
Constructors initialize objects when they are created. You can have multiple constructors to provide different ways to create objects.
public class Person { private String name; private int age; // Default constructor public Person() { this.name = "Unknown"; this.age = 0; } // Parameterized constructor public Person(String name, int age) { this.name = name; this.age = age; } }
Access modifiers control the visibility of class members:
Methods define the behavior of objects. They can access and modify instance variables.
public class Person { private String name; // Getter method - reads an instance variable public String getName() { return this.name; } // Setter method - modifies an instance variable public void setName(String name) { this.name = name; } }