Class in OOP
Sat, 07 Dec 2024
Today we are going to learn about classes and objects.Let's talk about classes.
In Object-Oriented Programming (OOP), a class is like a blueprint or template for creating objects (things that represent real-world entities). It defines the structure and behaviours that the objects created from it will have.Actually a class makes a new data type. For example, if we create a class named Student,then Student is one kind of user defined data type.We can assign different types of characteristics (built-in data types indeed).For example:
class Student
{
String Name;
int age;
float CGPA;
}
Besides we can also create methods(functions) inside the class.For example: we are willing to show the characteristics of the student.So,we need to write a funciton(method) for it.
class Student
{
String Name;
int age;
float CGPA;
public void DisplayInfo()
{
System.out.println("Student Name: " + Name);
System.out.println("Age: " + age);
System.out.println("CGPA: " + CGPA);
}
}
Note:Here we are seeing some things named public,private etc.These are called access specifiers.
public
: Accessible everywhere.private
: Accessible only within the defining class.protected
: Accessible within the package and by subclasses.Today we are going to learn about classes and objects.Let's talk about objects of classes.
In Object-Oriented Programming (OOP), an object is a specific instance of a class, representing a "thing" that has data and behavior.
Think of it Like This: A class is like a blueprint (e.g., a plan for a Student). An object is the actual thing created from that blueprint (e.g., an individual student with Name,age and CGPA).
public class Main {
public static void main(String[] args) {
Student student=new Student();
student.Name="Sakib";
student.age=23;
student.CGPA= (float) 4.00;
student.DisplayInfo();
}
}
Here 'student' is a object of Student class.We have assigned the values of the student.After tghat we are displaying the informations.
Now we will talk about constructors and destructors.
class Car {
String brand;
int speed;
Car() {
brand = "Unknown";
speed = 0;
}
Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
void display() {
System.out.println("Brand: " + brand + ", Speed: " + speed);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.display();
Car car2 = new Car("Toyota", 120);
car2.display();
}
}
This is a comment 1.
This is a comment 2.