In Java, a class is a fundamental component of object-oriented programming (OOP). It is a structure that serves as a model or blueprint to create objects. Objects are instances of classes, and classes define the attributes (variables) and methods (functions) that objects can have.
The basic structure of a class in Java is as follows:
public class MyClass {// attributes (variables)
String value1;
String value2;
// constructor (optional)
public MyClass(String value1, String value2) {
// initializing attributes with values passed as parameters
this.value1 = value1;
this.value2 = value2;
}
// methods
public void myMethod() {
// body method
// may include attribute manipulation and execution logic
}
}
Here are some key concepts associated with classes in Java:
Attributes (Instance Variables)
Represent the characteristics of the class. Each object created from the class will have its own sets of values for these attributes.
Methods
They are functions defined within the class that specify the behavior of objects in that class. They can perform operations, modify attributes and return values.
Builders
These are special methods called during the creation of an object. They are used to initialize the class attributes. If a constructor is not provided, Java automatically provides a default constructor.
Keyword "this"
Refers to the current instance of the class. It is used to distinguish between class attributes and method or constructor parameters when they have the same name.
Encapsulation
It is an OOP principle that suggests that the internal implementation details of a class should be hidden from external code. In Java, this is often achieved by using access modifiers such as private for attributes, which means they can only be accessed within the class itself.
Example of creating an object from a class:
MyClass myObject = new MyClass(value1, value2);
In this example, "MyClass" is the class, "myObject" is an object created from that class, and "value1" and "value2" are values that can be passed to the class constructor during object creation.
Nenhum comentário:
Postar um comentário