0% found this document useful (0 votes)
12 views15 pages

Class & Object in Java

Java is an Object-Oriented programming language that utilizes classes and objects as fundamental features, supporting key OOP concepts like inheritance and encapsulation. A class serves as a blueprint for creating objects, which are instances of the class containing methods and properties. The document provides examples and explanations of class and object syntax, variable types, and principles for designing classes in Java.

Uploaded by

ayushmaurya155
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views15 pages

Class & Object in Java

Java is an Object-Oriented programming language that utilizes classes and objects as fundamental features, supporting key OOP concepts like inheritance and encapsulation. A class serves as a blueprint for creating objects, which are instances of the class containing methods and properties. The document provides examples and explanations of class and object syntax, variable types, and principles for designing classes in Java.

Uploaded by

ayushmaurya155
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Classes & Objects

Java is an Object-Oriented programming language. In Java,


the classes and objects are the basic and important features of
object-oriented programming system, Java supports the
following fundamental
OOPs concepts –
• Classes

• Objects

• Inheritance

• Polymorphism

• Encapsulation

• Abstraction

• Instance

• Method

• Message Passing

What is Class in Java?

Class are a blueprint or a set of instructions to build a specific


type of object. It is a basic concept of Object-Oriented
Programming which revolve around the real-life entities. Class in
Java determines how an object will behave and what the object
will contain.

A class is a blueprint from which individual objects are created


(or, we can say a class is a data type of an object type).
In Java, everything is related to classes and objects.
Each class has its methods and attributes that can be accessed
and manipulated through the objects.
For example, if you want to create a class for students.
In that case, "Student" will be a class, and student records
(like student1, student2, etc) will be objects.
We can also consider that class is a factory (user-defined
blueprint) to produce objects.
Syntax of Class in Java
class <class_name>
{
field;
method;
}

Properties of Java Classes


A class does not take any byte of memory.
• A class is just like a real-world entity, but it is not a real-world

entity. It's a blueprint where we specify the functionalities.


• A class contains mainly two things: Methods and Data

Members.
• A class can also be a nested class.

• Classes follow all of the rules of OOPs such as inheritance,

encapsulation, abstraction, etc.

What is Object in Java?


Object is an instance of a class.
An object in OOPS is nothing but a self-contained component
which consists of methods and properties to make a particular
type of data useful.
For example color name, table, bag, barking. When you send a
message to an object, you are asking the object to invoke or
execute one of its methods as defined in the class.
From a programming point of view, an object in OOPS can
include a data structure, a variable, or a function.
It has a memory location allocated. Java Objects are designed as
class hierarchies.

Object Syntax in Java

ClassName ReferenceVariable = new ClassName();

Types of Java Class Variables


A class can contain any of the following variable types.
• Local variables − Variables defined inside methods,
constructors or blocks are called local variables. The
variable will be declared and initialized within the method
and the variable will be destroyed when the method has
completed.

• Instance variables − Instance variables are variables within


a class but outside any method. These variables are
initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or
blocks of that particular class.

• Class variables − Class variables are variables declared


within a class, outside any method, with the static keyword.
What is the Difference Between Object and Class in Java?
A Class in object oriented programming is a blueprint or
prototype that defines the variables and the methods (functions)
common to all Java Objects of a certain kind.
An object in OOPS is a specimen of a class. Software objects are
often used to model real-world objects you find in everyday life.
Understand the concept of Java Classes and Objects with an
example.
Let’s take an example of developing a pet management system,
specially meant for dogs. You will need various information about
the dogs like different breeds of the dogs, the age, size, etc.
You need to model real-life beings, i.e., dogs into software
entities.

Moreover, the million dollar question is, how you design such
software?
Here is the solution-
First, let’s do an exercise.
You can see the picture of three different breeds of dogs below.
Stop here right now! List down the differences between them.
Some of the differences you might have listed out maybe breed,
age, size, color, etc.
If you think for a minute, these differences are also some
common characteristics shared by these dogs.
These characteristics (breed, age, size, color) can form a data
members for your object.

Next, list out the common behaviors of these dogs like sleep, sit,
eat, etc. So these will be the actions of our software objects.
So far we have defined following things,
• Class – Dogs

• Data members or objects– size, age, color, breed, etc.

• Methods– eat, sleep, sit and run.

Now, for different values of data members (breed size, age, and
color) in Java class, you will get different dog objects.
You can design any program using this OOPs approach.

While creating a class, one must follow the following principles.

• Single Responsibility Principle (SRP)- A class should have


only one reason to change
• Open Closed Responsibility (OCP)- It should be able to
extend any classes without modifying it
• Liskov Substitution Responsibility (LSR)- Derived classes
must be substitutable for their base classes
• Dependency Inversion Principle (DIP)- Depend on
abstraction and not on concretions
• Interface Segregation Principle (ISP)- Prepare fine grained
interfaces that are client specific.

Classes and Objects in Java Example Programs


// Class Declaration
publicclassDog
{
// Instance Variables
String breed;
String size;
int age;
String color;
// method 1
public String getInfo()
{
return("Breed is: "+breed+" Size is:"+size+" Age is:"+age+"
color is: "+color);
}
public static void main(String[] args) {

Dog maltese=new Dog();


maltese.breed="Maltese";
maltese.size="Small";
maltese.age=2;
maltese.color="white";
System.out.println(maltese.getInfo());
}
}
This code is editable. Click Run to Compile + Execute

Output:
Breed is: Maltese Size is:Small Age is:2 color is: white

Java Object and Class Example: main outside class


In previous program, we are creating main() method inside the
class. Now, we create classes and define main() method in
another class. This is a better way than previous one.
// Class Declaration
class Dog {
// Instance Variables
String breed;
String size;
int age;
String color;
// method 1
public String getInfo() {
return ("Breed is: "+breed+" Size is:"+size+" Age is:"+age+"
color is: "+color);
}
}
public class Execute{
public static void main(String[] args) {
Dog maltese = new Dog();
maltese.breed="Maltese";
maltese.size="Small";
maltese.age=2;
maltese.color="white";
System.out.println(maltese.getInfo());
}
}
Output:
Breed is: Maltese Size is:Small Age is:2 color is: white
Difference Between Class and Object in Java:
CLASS OBJECT
A template for creating and An instance of a class.
instantiating objects within a
program.
Logical entity Physical entity
Declared with the “class” Created using the “new”
keyword. keyword.
A class does not get any Objects get memory when they
memory when it is created. are created.
A class is declared once. Multiple objects are created using
a class.
Consider mobile and remodel it into a software entity. A mobile
can have characteristics like color, model, battery backup, and
can perform actions like playing games, clicking photos,
messaging. So far, we have identified the following things:
Class Name: Mobile
Data Members: color, model, battery backup
Member Functions: playing games, clicking photos, messaging

Object and Class Example: Rectangle


There is given another example that maintains the records of
Rectangle class.
File: TestRectangle1.java

class Rectangle
{
int length;
int width;
void insert(int l, int w)
{
length=l;
width=w;
}
void calculateArea()
{
System.out.println(length*width);
}
}
class TestRectangle1
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

Example
public class A
{
void m1()
{
System.out.println("m1 in class A");
}
}
public class B extends A {
void m1() {
System.out.println("m1 in class B");
}
}
public class Test {
public static void main(String[] args)
{
B b = new B();
b.m1();

A a = new A();
a.m1();
A a2 = new B();
a2.m1();
}
}

Summary:
• Java Class is an entity that determines how Java Objects will

behave and what objects will contain


• A Java object is a self-contained component which consists

of methods and properties to make certain type of data


useful
• A class system allows the program to define a new class
(derived class) in terms of an existing class (superclass) by
using a technique like inheritance, overriding and
augmenting.

===================
public class Main
{
void main()
{
ClassA a1 = new ClassA();
//initialize the member data
//a1.x = 10;
// a1.y = 20;
a1.disp();
a1.add();

//another object
ClassA a2 = new ClassA();
//initialize the member data
//a2.x = 30;
// a2.y = 40;
a2.disp();
a2.add();
//

//create another object


ClassA a3 = new ClassA();
a3.intvalue(44,77);
a3.disp();
a3.add();
}
}

public class ClassA


{
private int x;// instance variable
private int y;//instance variable

void add()
{
int sum ; //local variable
sum = this.x+this.y;
System.out.println("Sum = "+sum);
}

void disp()
{
System.out.println("x = "+x+ " y = "+y);
}

void intvalue(int x, int y )


{
this.x = x;
this.y = y;
}
}
public class Student
{
int rollno;
String name;
float marks;
void disp()
{
System.out.println("\n ========\nrollno = "+rollno);
System.out.println("name = "+name);
System.out.println("marks = "+marks);
}
}

You might also like