Appearance
Java classes and objects
In Java programming, a class serves as a blueprint or template for creating objects. Classes define the structure and functionality of objects, providing a clear and organized way to represent real-world entities in your code.
Properties of a Class
Attributes (Properties)
Attributes, also known as properties or fields, represent the data associated with a class. They define the characteristics or state of objects created from the class. Attributes can be of various data types, such as integers, strings, or custom objects.
java
public class Car {
// Attributes
String make;
String model;
int year;
}
Methods (Behaviors)
Methods encapsulate the behavior or actions that objects of the class can perform. They define what objects can do or how they interact with other objects and the outside world. Methods can manipulate the object's data, perform calculations, or interact with other objects in the system.
java
public class Car {
// Attributes
String make;
String model;
int year;
// Method to display car information
public void displayInfo() {
System.out.println("Car: " + make + " " + model + " (" + year + ")");
}
}
Syntax for Creating a Class
A Java class typically follows this structure:
java
public class ClassName {
// Attributes
dataType attributeName1;
dataType attributeName2;
// Constructor
public ClassName(parameter1, parameter2) {
// Constructor code
}
// Methods
returnType methodName1(parameter1, parameter2) {
// Method code
}
returnType methodName2(parameter1, parameter2) {
// Method code
}
// Additional methods
}
Creating Objects from a Class
Once you've defined a class, you can create objects (instances) of that class in your code. Each object has its own set of attributes and methods, independent of other objects created from the same class.
Example: Creating Objects from the Car Class
java
public class Main {
public static void main(String[] args) {
// Creating objects of the Car class
Car myCar1 = new Car();
Car myCar2 = new Car();
// Setting attributes for each car object
myCar1.make = "Toyota";
myCar1.model = "Camry";
myCar1.year = 2020;
myCar2.make = "Honda";
myCar2.model = "Accord";
myCar2.year = 2019;
// Calling methods on each car object
myCar1.displayInfo(); // Output: Car: Toyota Camry (2020)
myCar2.displayInfo(); // Output: Car: Honda Accord (2019)
}
}
Java classes provide the structure and blueprint for creating objects in your code. By defining attributes and methods within a class,Objects created from a class inherit these attributes and methods, allowing you to model real-world entities and build modular, reusable code.