Hello, I'm @toufiq777
Hope everyone is well I am also fine by the grace of God.
I want to share my views and knowledge with you all on the topic of Intro to Classes and objects in Java. so let's get started---
Classes and Objects:
Everything is based on a fundamental theory. In Java there are two fundamental concepts of OOP. They are classes and objects. We can say this class is the basic to create objects in Java. For objects, they are the specific instances of class. Let me share an example to make it clearer.
In a class called Car. We can present the common features of cars like their color, brand, speed, performance, etc..
An object that has been created from the Car class could be a specific car, like a white Toyota which has a top speed of 200 km/h.
Defining a Class in Java
if we want to define a class in Java, we can use the class keyword. We can define instance variables (attributes) and methods (actions) in a class.
This example can make it clear:
public class Book {
String title; // Instance variable
String author; // Instance variable
int pages; // Instance variable
void readBook() { // Method
System.out.println("Reading " + title);
}
}
Creating an Object from a Class
We can create an object by using new keyword with the class name.
Example:
public class Main {
public static void main(String[] args) {
Book myBook = new Book(); // Creating an object
myBook.title = "Java Programming"; // Assigning values
myBook.author = "John Doe";
myBook.pages = 350;
System.out.println("Title: " + myBook.title);
System.out.println("Author: " + myBook.author);
System.out.println("Pages: " + myBook.pages);
myBook.readBook(); // Calling a method
}
}
Instance Variables and Methods
Instance Variables: Instance variables are data specific to an object. Each object has its copy of instance variables.
Methods: It defines behaviors or actions that an object can perform. instance variables are often used.
Constructors and Destructors
Constructors: a special method used to initialize objects is called a constructor. The same name is being used as the class and there is no return type.
Example:
public class Book {
String title;
String author;
// Constructor
public Book(String t, String a) {
title = t;
author = a;
}
}
Usage:
Book myBook = new Book("Java Programming", "John Doe");
Destructors: There are no explicit destructors in Java like some other languages. For that, memory is automatically managed by the garbage collector, it cleans objects that have no use.
From the above texts, we learned about a class, Instance variables, constructors, and garbage collectors. These are the basic concepts that we need to build to have a solid foundation in Java.
I am inviting my friends @sohanurrahman
@aslamarfin and @rahul989 to participate in this challenge.
Thank you
@toufiq777