What is a Class?
A class is a blueprint or template for creating objects in Java. It defines properties (fields) and methods (behaviors) that objects created from the class will have.
In Java, everything is part of a class, and the class contains fields (attributes) and methods (functions) to perform actions.
Example:
public class Car {
// Instance variables (properties)
String color;
String model;
// Constructor (initializer for the class)
public Car(String color, String model) {
this.color = color;
this.model = model;
}
// Method (defines behavior)
void drive() {
System.out.println("The " + color + " " + model + " is driving.");
}
}
In this example, the `Car` class defines two properties (`color`, `model`) and a method (`drive`) to simulate behavior.
What is an Object?
An object is an instance of a class. It has a state (attributes defined in the class) and behavior (methods defined in the class).
Example:
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car("Red", "Toyota");
// Calling the method using the object
myCar.drive(); // Output: The Red Toyota is driving.
}
}
In the above code, `myCar` is an object of the `Car` class, and we use this object to call the `drive()` method.
Class Variables (Fields)
Class variables (fields) are properties that represent the state of an object. They are declared within a class but outside methods or constructors.
Example:
public class Person {
// Instance variables (fields)
String name;
int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
Here, the `name` and `age` fields represent the state of the `Person` object.
Types of Variables in Java
Java has three types of variables:
- Local variables: Declared inside methods, constructors, or blocks. These variables are used within that scope only.
- Instance variables: Declared inside the class, but outside methods. They represent the state of an object and are specific to each object.
- Static variables: Declared with the
statickeyword. They are shared across all instances of the class.
Differences Between Types of Variables in Java
In Java, variables can be categorized into three types: Instance Variables, Class Variables, and Local Variables.
| Variable Type | Description | Example | Scope | Memory Allocation | Default Value |
|---|---|---|---|---|---|
| Instance Variable | These variables are declared inside a class but outside any method. Each instance (object) of the class has its own copy of the instance variable. | public class MyClass { int x; } |
Accessible by all non-static methods and constructors within the class. Each object has its own copy of the variable. | Memory is allocated when an object is created. | Instance variables are given default values depending on their type (e.g., 0 for int, null for objects). |
| Class Variable (Static Variable) | These variables are declared with the static keyword. They belong to the class rather than instances of the class and are shared by all objects of that class. |
public class MyClass { static int count; } |
Accessible by static methods and non-static methods (using an object reference). Shared by all instances of the class. | Memory is allocated when the class is loaded into memory, not when objects are created. | Static variables also have default values (e.g., 0 for int, null for objects). |
| Local Variable | These variables are declared inside methods, constructors, or blocks. They are only accessible within the method, constructor, or block where they are declared. | public void myMethod() { int localVar; } |
Accessible only within the method, constructor, or block where they are defined. | Memory is allocated when the method is called and deallocated when the method execution finishes. | Local variables must be initialized before use. They do not have default values. |
Constructors in Java
A constructor is a special method used to initialize objects. It is called when an object is created. There are two main types of constructors:
- Default Constructor: A constructor provided by the compiler if no constructor is explicitly defined. It initializes instance variables to default values.
- Parameterized Constructor: A constructor that allows you to pass values to initialize instance variables with custom values when the object is created.
Differences Between Default and Parameterized Constructors:
| Feature | Default Constructor | Parameterized Constructor |
|---|---|---|
| Initialization | Initializes with default values (e.g., 0, null) | Initializes with specified values passed as arguments |
| Arguments | No arguments | Requires arguments |
| Example | public Car() { this.color = "Red"; } |
public Car(String color) { this.color = color; } |
Example:
// Default constructor
public class Book {
String title;
String author;
public Book() {
title = "Unknown";
author = "Unknown";
}
// Parameterized constructor
public Book(String title, String author) {
this.title = title;
this.author = author;
}
void display() {
System.out.println("Title: " + title + ", Author: " + author);
}
}
Here, the class `Book` has both a default and parameterized constructor.
Methods in Java
Methods in Java define the behavior of objects. They can accept input parameters and return a result. Methods are used to perform operations on data within an object.
Method Syntax in Java
Methods in Java are blocks of code that perform a specific task. They are defined within a class and can have different signatures depending on whether they return a value and whether they take parameters.
General Syntax of a Method:
returnType methodName(parameterList) {
// Method body
}
Where:
- returnType: Specifies what type of value the method returns (e.g.,
int,String,voidif it does not return anything). - methodName: The name of the method.
- parameterList: A list of parameters (if any) the method accepts. If there are no parameters, you can leave the parentheses empty.
1. Method with No Return Value and No Parameters
This type of method doesn't return any value and does not accept any parameters.
public class MyClass {
// Method with no return value and no parameters
public void printMessage() {
System.out.println("Hello, this is a method with no return value and no parameters.");
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.printMessage(); // Calling the method
}
}
In the above example, the printMessage method does not return anything and does not require any parameters.
2. Method with No Return Value and With Parameters
This type of method doesn't return any value but accepts parameters to perform its task.
public class MyClass {
// Method with no return value and parameters
public void displayMessage(String message) {
System.out.println(message);
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.displayMessage("This is a message with a parameter."); // Calling the method with a parameter
}
}
Here, the displayMessage method takes a String parameter and prints it. It doesn't return anything.
3. Method with Return Value and No Parameters
This method returns a value but does not accept any parameters. It is useful when you want to return data from the method.
public class MyClass {
// Method with return value and no parameters
public int getNumber() {
return 42;
}
public static void main(String[] args) {
MyClass obj = new MyClass();
int num = obj.getNumber(); // Calling the method and storing the returned value
System.out.println("Returned value: " + num); // Output: 42
}
}
In this example, the getNumber method returns an integer value, but does not take any parameters.
4. Method with Return Value and With Parameters
This method returns a value and also takes parameters. It is useful when you need to perform some calculation or operation and return a result based on the input parameters.
public class MyClass {
// Method with return value and parameters
public int addNumbers(int a, int b) {
return a + b;
}
public static void main(String[] args) {
MyClass obj = new MyClass();
int result = obj.addNumbers(5, 3); // Calling the method with parameters
System.out.println("The sum is: " + result); // Output: 8
}
}
Here, the addNumbers method takes two integers as parameters and returns their sum.
Different Method Signatures:
- Method Overloading: Multiple methods with the same name but different parameter types or numbers.
- Static Methods: Methods that belong to the class and can be called without creating an instance of the class.
- Non-static Methods: Methods that belong to an object and require an instance of the class to be called.
Example:
public class Calculator {
// Method overloading example
public int add(int num1, int num2) {
return num1 + num2;
}
public double add(double num1, double num2) {
return num1 + num2;
}
// Static method
public static void displayMessage() {
System.out.println("This is a static method");
}
// Non-static method
public void subtract(int num1, int num2) {
System.out.println("Result: " + (num1 - num2));
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 3)); // Output: 8
System.out.println(calc.add(5.5, 3.3)); // Output: 8.8
Calculator.displayMessage(); // Output: This is a static method
calc.subtract(10, 5); // Output: Result: 5
}
}
In this example:
- The
addmethod is overloaded to accept bothintanddoubleparameters. - The
displayMessagemethod is static and called using the class name. - The
subtractmethod is non-static and requires an instance of the class.
Static Methods vs Non-static Methods
In Java, methods can either be static or non-static.
Static Methods
A static method belongs to the class, rather than instances of the class. You can call a static method without creating an object of the class. Static methods are often used for utility or helper functions.
public class MyClass {
// Static method
public static void staticMethod() {
System.out.println("This is a static method.");
}
public static void main(String[] args) {
MyClass.staticMethod(); // Calling static method without creating an object
}
}
The static method staticMethod is called directly on the class without needing to create an instance of the class.
Non-static Methods
A non-static method belongs to an instance of the class. You need to create an object of the class to call a non-static method.
public class MyClass {
// Non-static method
public void nonStaticMethod() {
System.out.println("This is a non-static method.");
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.nonStaticMethod(); // Calling non-static method using an object
}
}
The non-static method nonStaticMethod is called using an instance of the class, which is obj in this case.
Blocks in Java
In Java, there are three types of blocks:
- Instance Block: Runs every time an object is created. It's used for common initialization tasks for every instance.
- Static Block: Runs only once when the class is loaded into memory. It is used for static initialization tasks.
- Local Block: Defined inside methods or constructors to limit the scope of variables to that block.
Instance Block:
public class Example {
{
// Instance Block
System.out.println("Instance Block: Object Created");
}
public static void main(String[] args) {
Example obj = new Example(); // Output: Instance Block: Object Created
}
}
Static Block:
public class StaticExample {
static {
// Static Block
System.out.println("Static Block: Class Loaded");
}
public static void main(String[] args) {
StaticExample obj = new StaticExample(); // Output: Static Block: Class Loaded
}
}
Local Block:
public class LocalBlockExample {
public void display() {
// Local Block
{
int x = 10;
System.out.println("Value of x: " + x);
}
}
public static void main(String[] args) {
LocalBlockExample obj = new LocalBlockExample();
obj.display(); // Output: Value of x: 10
}
}