In Java, a class is a blueprint or template for creating objects. It encapsulates data for the object attributes and the behaviour of the object methods.
It defines the structure and behaviour of objects by specifying attributes (data fields) and methods (functions) that the objects will have.
Here's an overview of classes in Java:
To declare a class in Java, we can use the "class" keyword followed by the name of the class.
public class YourClassName { // Class members (attributes and methods) go here }
Attributes represent the data or state of objects. They are also called data fields or member variables.
public class Vehicle { // Attributes String manufacturer; String model; int year; }
Attributes are declared within the class and specify the properties of objects of that class.
public class Vehicle { // Attributes String manufacturer; String model; int year; // Methods public void brake() { // Code to brake the Vehicle } // Methods public void start() { // Code to start the Vehicle } public void accelerate() { // Code to accelerate the Vehicle } }
Methods define the behaviour of objects. They represent actions that objects of the class can perform.
Methods are declared within the class and contain executable code.
class YourClassName { public String publicAttribute = "public attribute"; private String privateAttribute = "private attribute"; public void publicMethod() { // Code accessible from outside the class System.out.println(publicAttribute); } private void privateMethod() { // Code accessible only within the class System.out.println(privateAttribute); } } public class Main { public static void main(String[] args) { YourClassName yourClassName = new YourClassName(); yourClassName.publicMethod(); // Output: public attribute // error: privateMethod() has private access in YourClassName // yourClassName.privateMethod(); } }
Access modifiers control the visibility of classes, attributes, and methods. Java provides four access modifiers: public, protected, private, and the default (package-private).
These modifiers determine whether a class, attribute, or method can be accessed from other classes or packages.
Classes provide a way to organize and structure code in Java, making it easier to manage and maintain large-scale software projects.
They encapsulate data and behaviour into reusable components and promote modularity, abstraction, and code reusability.