Class:- A class is a blueprint or template for creating objects. It defines the structure, attributes (data members), and behaviors (methods) that objects of the class will have. A class can contain fields (variables) to represent the state of objects and methods to define their behavior. Classes are used to encapsulate related data and functions into a single unit.
Properties of Java Classes
Components of Java Classes
In general, class declarations can include these components, in order:
In Java, you define a class using the class keyword followed by the class name. For example:
Syntax :-
public class Class-Name
{
//Write Class members (fields and methods) here.
}
Example :-
public class Age
{
// Fields or instance variables
int Age=30;
// Methods
void MyMathod()
{
System.out.println(“Hello, my Age is ” + Age);
}
}
Object:
There are 3 ways to initialize object in Java.
1. Using by Reference Variable :-
ClassName variableName;
variableName = new ClassName();
Example :-
public class MyClass
{
// Fields and methods of the class
}
public class Main
{
public static void main(String[] args)
{
MyClass myObject; // Declare a reference variable of type MyClass
myObject = new MyClass(); // Create an instance of MyClass and assign it to the reference variable
}
}
2. Using Factory Methods:- In some cases, you may use factory methods to create and initialize objects. Factory methods are static methods within a class that return an instance of that class. These methods can provide more flexibility in creating objects and may include custom initialization logic. Objects can access the fields and methods defined in their class.
Here’s an example:
public class MyClass
{
private int value;
// Factory method
public static MyClass createInstance(int value)
{
MyClass obj = new MyClass();
obj.value = value;
return obj;
}
public static void main(String[] args)
{
MyClass obj = MyClass.createInstance(42); // Object initialized using a factory method
}
}
3. Using Constructors:- The most common way to initialize an object is by using constructors. Constructors are special methods within a class that are called when you create a new instance of that class using the new keyword. You can define your own constructors in your classes to initialize the object with specific values.
Here’s an example:-
public class MyClass
{
private int value;
// Constructor
public MyClass(int value)
{
this.value = value;
}
public static void main(String[] args)
{
MyClass obj = new MyClass(42); // Initializing with a constructor
}
}
Syntax :-
Class_Name Object_Name = New Class_Name(); //
Example :-
public class Main
{
void myMathod()
{
String Name;
Int Age;
}
public static void main(String[] args)
{
// Create objects
Main person1 = new Main(); // persion1 is objects.
Main person2 = new Main(); // persion1 is objects.
// Set data for objects
person1.name = “Alice”;
person1.age = 30;
person2.name = “Bob”;
person2.age = 25;
// Calling methods on objects
person1. myMathod();
person2. myMathod();
}
}