Java-Classes and Objects
2 min readDec 28, 2023
Classes and objects are the two main aspects of object-oriented programming(OOP)
- class is a template or blueprint for an objects. it’s describes the states and behaviors of it’s object
- An object is an instance of a class. Object has states and behaviors
For example:- In real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.
A Class is like an object constructor, or a “blueprint” for creating objects.
Create the class ( Car as a class)
class Car{
String color
String size;
String model;
String engine;
}
//Save it as Car.java
Adding method
class Car{
String color;
String size;
String model;
String engine;
void start(){ //This is a simple method to display a text
System.out.println("BMW");
}
}
Create an object
class Car{
String color;
String size;
String model;
String engine;
void start(){
System.out.println("car1");
}
public static void main(string args[]){
Car car1=new Car(); // create an object.
}
}
Assign values to instance variables
class Car{
String color;
String size;
String model;
String name;
void start(){
System.out.println("car1");
}
Public static void main(string args[]){
Car car1=new Car();
car1.name = "BMW";
car1.size = "4319 x 1799 x 1434 mm";
car1.color = "black";
car1.model = "BMW i7";
}
}
Display the value of instance variables of the object
class Car{
String color;
String size;
String model;
String name;
void start(){
System.out.println("car1");
}
public static void main(string args[]){
Car car1=new Car();
car1.name = "BMW";
car1.size = "4319 x 1799 x 1434 mm";
car1.color = "black";
car1.model = "BMW i7";
System.out.println ("car1 name:"+ car1.name);
System.out.println ("car1 name:"+ car1.size);
System.out.println ("car1 name:"+ car1.model);
System.out.println ("car1 name:"+ car1.color);
}
}
Thanks for reading this article!!!😊💖 Hope you will enjoy.
Leave a comment below ( this my first article✍)