Fundamentals of object-oriented programming
What Are Objects?
What Are Classes?
public class Cat { /* Instance variables: states of Cat */ String name; int age; String color; String breed; /* Instance methods: behaviors of Cat */ void sleep(){
System.out.println("Sleeping");
} void play(){ System.out.println("Playing"); } void feed(){ System.out.println("Eating"); }
}
Now we have successfully defined a template for Cat. Let’s say we have two cats named Thor and Rambo.
public class Main {
public static void main(String[] args) {
Cat thor = new Cat();
Cat rambo = new Cat();
}
}
Next, we’ll define their states and behaviors.
public class Main { public static void main(String[] args) { /* Creating objects */ Cat thor = new Cat(); Cat rambo = new Cat(); /* Defining Thor cat */ thor.name = "Thor"; thor.age = 3; thor.breed = "Russian Blue"; thor.color = "Brown"; thor.sleep(); /* Defining Rambo cat */ rambo.name = "Rambo"; rambo.age = 4; rambo.breed = "Maine Coon"; rambo.color = "Brown"; rambo.play(); } }
Like the above code examples, we can define our class, instantiate it (create objects) and specify the states and behaviors for those objects.
No.
Object
Class
1)
Object is an instance of a class.
Class is a blueprint or template from which objects are created.
2)
Object is a real world entity such as pen, laptop, mobile, bed, keyboard, mouse, chair etc.
Class is a group of similar objects.
3)
Object is a physical entity.
Class is a logical entity.
4)
Object is created through new keyword mainly e.g.
Student s1=new Student();Class is declared using class
keyword e.g.
class Student{}5)
Object is created many times as per requirement.
Class is declared once.
6)
Object allocates memory when it is created.
Class doesn't allocated memory when it is created.
7)
There are many ways to create object in java such as new keyword, newInstance() method, clone() method, factory method and deserialization.
There is only one way to define class in java using class keyword.
Now, we have covered the basics of object-oriented programming. Let's move on to the principles of object-oriented programming.Principles of object-oriented programming
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into reusable objects that interact with each other. It provides a way to structure and design software by representing real-world objects and their relationships
- Encapsulation
- Inheritance
- Abstraction
- Polymorphism
Difference Between Object Based and Object Oriented Languages
Object Based Language |
Object Oriented Language |
|
Support of features |
Object Based
Language does not support all the features of Oops |
Object Oriented
Language supports all the features of Oops. |
Inheritance |
Object Based
Language Does Not Support Oops feature i.e. Inheritance. |
Object Oriented
Language supports all the Features of Oops including Inheritance. |
Sample |
Visual Basic is an
Object based Programming Language because you can use class
and Object here but can not inherit one class from another class i.e. it does
not support Inheritance. |
Java is an Object
Oriented Languages because it supports all the concepts of Oops like Data
Encapsulation, Polymorphism,Inheritance,Data Abstraction , Dynamic Binding
etc. |
Example |
Javascript, VB
are example of Object Based Language. |
C#, Java, VB. Net
are example of Object Oriented Languages. |
Advantages of OOPS:
5) improve the overall design and structure of their software.
Encapsulation:Encapsulation is a process of wrapping data and methods together into a single unit that can operate on data within a class.𝗘𝗻𝗰𝗮𝗽𝘀𝘂𝗹𝗮𝘁𝗶𝗼𝗻: Encapsulation is the mechanism of hiding the internal details and implementation of an object from the outside world. It ensures that the object's internal state can only be accessed through well-defined methods (getters and setters), providing data security and abstractionEssentially, it is the idea of hiding data within a class, preventing anything outside that class from directly interacting with it.Members of other classes can interact with the attributes of another object through its methods.Remember methods are the functions defined within the class.It's just like a capsule that contains a mix of several medicines, and is a technique that helps keep instance variables protected.This can be achieved by using private
access modifiers that can’t be accessed by anything outside the class. In order to access private states safely, we have to provide public getter and setter methods. Getter methods are used to retrieving information and setter methods are used to change the information of the members.Let’s say there is a record shop that sells music albums of different artists and a stock keeper who manages them.
Figure 4: Class diagram without encapsulation
If you look at figure 4, theStockKeeper
class can access theAlbum
class’s states directly asAlbum
class’s states are set topublic
.What if the stock keeper creates an album and sets states to negative values? This can be done intentionally or unintentionally by a stock keeper.To illustrate, let’s see a sample Java program that explains the above diagram and statement.Album class:
public class Album { public String name; public String artist; public double price; public int numberOfCopies; public void sellCopies(){ if(numberOfCopies > 0){ numberOfCopies--; System.out.println("One album has sold!"); } else{ System.out.println("No more albums available!"); } } public void orderCopies(int num){ numberOfCopies += num; } }
StockKeeper class:
public
{
class StockKeeper
public String name;
public StockKeeper(String name){
this.name = name;
}public void manageAlbum(Album album, String name, String artist, double price, int numberOfCopies){
/* Defining states and behaviors for album */ album.name = name; album.artist = artist; album.price = price; album.numberOfCopies = numberOfCopies; /* Printing album details */ System.out.println("Album managed by :"+ this.name); System.out.println("Album details::::::::::"); System.out.println("Album name : " + album.name); System.out.println("Album artist : " + album.artist); System.out.println("Album price : " + album.price); System.out.println("Album number of copies : " + album.numberOfCopies); } }
Main class:
public
class Main {
public static void main(String[] args) {
StockKeeper johnDoe = new StockKeeper("John Doe"); /* Stock keeper creates album and assigns negative values for price and number of copies available */ johnDoe.manageAlbum(new Album(), "Slippery When Wet", "Bon Jovi", -1000.00, -50); } }
Output:
Album managed by :John Doe Album details:::::::::: Album name : Slippery When Wet Album artist : Bon Jovi Album price : -1000.0 Album number of copies : -50
public class Album {
private String name;
private String artist;
private double price;
private int numberOfCopies;
public void sellCopies(){
if(numberOfCopies > 0){
numberOfCopies--;
System.out.println("One album has sold!");
}
else{
System.out.println("No more albums available!");
}
}
public void orderCopies(int num){
numberOfCopies += num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if(price > 0) {
this.price = price;
}
else {
this.price = 0.0;
}
}
public int getNumberOfCopies() {
return numberOfCopies;
}
public void setNumberOfCopies(int numberOfCopies) {
if(numberOfCopies > 0) {
this.numberOfCopies = numberOfCopies;
}
else {
this.numberOfCopies = 0;
}
}
}
StockKeeper class:
public class StockKeeper {
private String name;
StockKeeper(String name){
setName(name);
}
public void manageAlbum(Album album, String name, String artist, double price, int numberOfCopies){
/*
Defining states and behaviors for album
*/
album.setName(name);
album.setArtist(artist);
album.setPrice(price);
album.setNumberOfCopies(numberOfCopies);
/*
Printing album details
*/
System.out.println("Album managed by :"+ getName());
System.out.println("Album details::::::::::");
System.out.println("Album name : " + album.getName());
System.out.println("Album artist : " + album.getArtist());
System.out.println("Album price : " + album.getPrice());
System.out.println("Album number of copies : " + album.getNumberOfCopies());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Main class:
public class Main {
public static void main(String[] args) {
StockKeeper johnDoe = new StockKeeper("John Doe");
/*
Stock keeper creates album and assigns negative values for price and number of copies available
*/
johnDoe.manageAlbum(new Album(), "Slippery When Wet", "Bon Jovi", -1000.00, -50);
}
}
Output:
Album managed by :John Doe
Album details::::::::::
Album name : Slippery When Wet
Album artist : Bon Jovi
Album price : 0.0
Album number of copies : 0
Advantages of encapsulation in Java
- We can make a class read-only or write-only: for a read-only class, we should provide only a getter method. For a write-only class, we should provide only a setter method.
- Control over the data: we can control the data by providing logic to setter methods, just like we restricted the stock keeper from assigning negative values in the above example.
- Data hiding: other classes can’t access private members of a class directly.
Real Time
Example:
ü
Ink is the important
component in pen but it is hiding by some other material
ü
Medical capsule
Let's consider capsule. If combinations of medicine are
variables and methods then the
capsule will act as a class and the whole process is called
Encapsulation.
School bag is
one of the most real examples of Encapsulation. School bag can keep
our books,
pens etc.
First
Real-time example:
When you log
into your email account such as Gmail, Yahoo mail, Rediff mail etc then there
is a lot of internal processes taking place in
the backend. and you have no control over it.
When you enter the password for logging
then they are retrieved in an encrypted form and
verified and
then you are given the access to your account. You do not have control over it
that how the
password is verified and this keeps it safe from misuse.
Second Real-time Example:
Suppose you
have an account in the bank. If your balance variable is defined as a public
variable in
the bank software then your account balance will be known public then,
in this case, anyone can know your account
balance. So do you like it? Obviously No.
So for making your account safe, they declare balance variable as private
so that
anyone cannot
see your account balance and the person who have to see account
balance then
they will have to access private members only through methods
defined inside
that class and this method will ask your account holder name or user Id,
or
password for authentication.
Thus, security
is achieved by utilizing the concept of data hiding. This is
called Encapsulation.
How to achieve Encapsulation in java?
OR
How
to implement Encapsulation in java?
➝ Declaring the instance variable of the class as private. so that
it cannot be accessed
directly by
anyone from outside the class.
➝ Provide the public setter and getter methods
in the class to set/modify the values of the
variable/fields.
Since getter and setter methods are widely used in Java programming but not everyone
understands and implements these methods
properly. So I would like to understand about
getter and
setter methods clearly.
What are getter and setter methods?
In Java. the
setter method is a method which is used for updating values of a variable.
This method is also known as mutator
method. Whereas getter method is a method
which is used to retrieve the value of a
variable or return the value of the private
member
variable. This method is also known as an accessor method.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.