Class and Object
Class and Object
Java is an object-oriented programming language. Classes and objects are fundamental building
blocks.
This presentation covers:
o Class fundamentals
o Declaring objects
o Assigning object reference variables
o Adding methods to a class
Class Fundamentals
We are using classes and objects in programming to solve the real world problem through
coding.
A class is a blueprint for creating objects. (Without Class we cannot create objects)
So for creating any object like Car,Mobile ,Pen etc we have to Specify its Properties like
Model, Color, Size And the Functions like automatic manual… etc. These are specifying
inside the class.
So in programming the Objects are all the entities like Object(Car ,pen…), Person, Animal or
anything.
Different object have different properties like Pen (Color ,size, type(gel pen ball pen..)
class ClassName
{
// Fields (Instance Variables- that hold object data)
DataType variableName;
ReturnType methodName() {
// Method body
}
}
class → Keyword used to define a class.
ClassName → class name should be start with upper case letter. Ex Student, Parent, MyClass
Example of a Class
The example below demonstrates a simple Java class named Car with attributes and a method.
Code Example:
class Car {
String model; // Stores the car's model name
int year; // Stores the car's manufacturing year
Declaring Objects
Example:
Car myCar = new Car();
Summary
returnType → The data type of the value the method will return (e.g., int, double,
String,Boolean….)
Example:-
public class Example {
// Method returning an integer
public int getNumber() {
return 10;
}
// Method returning a double
public double getPrice() {
return 99.99;
}
// Method returning a boolean
public boolean isAvailable() {
return true;
}
}
class Calculator {
// Method to add two numbers and return the result
int add(int a, int b) {
return a + b; // Returns the sum of a and b
}
}