In this tutorial, we'll build a simple Java class called Person
that demonstrates the basics of object-oriented programming (OOP). This example introduces key concepts such as class definition, instance variables, constructors, methods, and the main
method for executing your program.
The Code Example
Below is a complete Java code snippet for the Person
class:
public class Person {
private String name;
private int age;
// Constructor to initialize the Person object
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter for name
public String getName() {
return name;
}
// Getter for age
public int getAge() {
return age;
}
// Overriding the toString method for custom output
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
// Main method to run the application
public static void main(String[] args) {
Person person = new Person("Alice", 30);
System.out.println(person);
}
}
Breaking It Down
Class Definition and Instance Variables
Class Declaration:
public class Person { ... }
This line defines a new class namedPerson
.Instance Variables:
private String name;
andprivate int age;
These variables hold data specific to eachPerson
object. Marking them asprivate
enforces encapsulation, ensuring that these fields can only be accessed or modified through designated methods.
Constructor
- Constructor Method:
The constructor is used to initialize thepublic Person(String name, int age) { this.name = name; this.age = age; }
Person
object with a name and age when it is created.
Getters
- Access Methods:
These methods allow external code to access the private fields while preserving the integrity of the data.public String getName() { return name; } public int getAge() { return age; }
Overriding toString()
- Custom String Representation:
By overriding the@Override public String toString() { return "Person{name='" + name + "', age=" + age + "}"; }
toString()
method, you specify how aPerson
object should be represented as a string. When printing the object, this custom format is used automatically.
Main Method
- Entry Point:
Thepublic static void main(String[] args) { Person person = new Person("Alice", 30); System.out.println(person); }
main
method serves as the entry point of the application. It creates aPerson
object and prints it, invoking the overriddentoString()
method to display the output.
Conclusion
With this simple example, you've learned how to create a Java class, define private instance variables, initialize objects using a constructor, provide access to data via getter methods, and override the toString()
method for custom output. Mastering these fundamental concepts is essential as you progress towards building more complex Java applications.
Happy coding!
Comments
Post a Comment