Last chance! 50% off DataCamp Premium
Sale ends in
The class keyword in Java is fundamental to the language's object-oriented programming model. It is used to define a new class, which can contain fields (variables) and methods to define the behavior of objects created from the class.
A class serves as a blueprint for creating objects. It encapsulates data for the object and methods to manipulate that data.
class ClassName {
// fields
// methods
}
ClassName: The name of the class, which should start with an uppercase letter by convention.fields: Variables that hold the state of the class.methods: Functions that define the behavior of the class.class Animal {
String name;
int age;
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Animal();
dog.name = "Buddy";
dog.age = 5;
dog.displayInfo();
}
}
In this example, the Animal class has two fields, name and age, and one method, displayInfo(). The Main class demonstrates creating an Animal object and setting its fields.
class Car {
String model;
int year;
// Constructor
Car(String model, int year) {
this.model = model;
this.year = year;
}
void displayDetails() {
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota", 2020);
car.displayDetails();
}
}
This example introduces a constructor in the Car class to initialize the model and year fields. The Main class creates a Car object using the constructor and displays its details.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound();
}
}
This example demonstrates inheritance. The Dog class extends the Animal class and overrides the makeSound() method. The Main class creates a Dog object and calls the overridden method.
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}