Design a site like this with WordPress.com
Get started

Class and Object

Java is an object oriented programming language, each program is represented in terms of object. So an object is any real world object for e.g. a Car, Computer, Apple etc.

To understand it better, lets say we are given a program to read file from the system from a given specified location. So how do we represent a file and how do we represent its behavior ? Like a file is supposed to read, write or possible delete ? how do we represent all of this ?

In an OOP (Object oriented programming) we would represent a File and its behavior in a class. For e.g.

class File {
String fileName;

File(String fileName){
this.fileName = fileName;
}

public void read(){
 ...
}

public void write() {
 ..
}

}

So a class represents everything a file object can do. So in our example, a file can read and write.

So if we have to read a file, we have to create an instance of the file object, like below.

File myfile = new File("sample.txt")
myfile.read();

So now we have created a new instance of the File class which is represented by variable “myfile”. The variable “myfile” uniquely represents the file “sample.txt” and when we can call read/write method on the “myfile” instance and it will execute the code inside the methods read()/write() of the file class.

So the green box represents “Class” and all the yellow boxes represent “Object/Instances” of the class “File”. We can have as many objects of the class File as we want.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: