OOPS Concepts
What is OOPS?
Object Oriented Programming Concepts (OOPS) is a programming paradigm using "objects" to design applications. In yet simpler terms, it is like building a group of co-operating objects that accomplish desired tasks.
Classes and Objects:
Object is any real world entity that participates in some activity within a system.
When you design a class, think about the objects that
will be created from that class type. Think about:
Things the object knows
Things the object does
For example, within Banking system, Customer is an object which participates in day to day activity. Since Object Oriented Programming implements the behavior and interaction of real world objects, real world objects should be used as an object in Programming.
Customer in Banking system may have first name, last name, address and based on activity and account balance you can consider it as Regular customer or Premium Customer, etc.
Bank may have more than one customer and each customer has unique account number. Similar way, in programming when you create customer objects, each will have its own account number and properties like first name, last name, address etc.
Also a customer may do some things like he may withdraw amount, deposit amount, apply for loan, etc.
Things that object knows about itself are called instance variables.
Things that objects does are called methods.
Thus, to summarize, objects have instance variables and methods, but those are also a part of the class.
NOTE:
So class is not an object, but is used to construct an object. Thus, a class is a blue print for an object. It tells the JVM how to create the object of that particular type.
Thus, to summarize, objects have instance variables and methods, but those are also a part of the class.
NOTE:
So class is not an object, but is used to construct an object. Thus, a class is a blue print for an object. It tells the JVM how to create the object of that particular type.
Making an Object:
public class Customer { /** * Creating instance variables. What object knows. */ int accNo; String firstName; String lastName; String address; String email; double mobileNo; /** * Creating methods. What object does. */ void withdrawAmt() { System.out.println("Withdrawing Amount"); } void depositAmt() { System.out.println("Depositing Amount"); } /** * Main Method to test our Customer class */ public static void main(String args[]) { Customer customer =new Customer(); /** * Using the dot operator we set the account Number */ customer.accNo=578598; /* * Calling withdrawAmt() method of Customer */ customer.withdrawAmt(); } }
**NOTE**:
Often I have seen confusion with people as to what does the below statement exactly is and does:
Customer customer =new Customer();
Stick these few points:
1. There is nothing like object variable.
2. There is only a object reference variable (In our case it is customer).
An object reference variable holds a way (address) to access that object. Consider it like a pointer to that object.
3. Think of the customer reference variable as a remote control to access the instance variables and methods of the Customer object by using the Dot (.) operator.
Encapsulation:
We saw above how we can access instance variables and methods of a class.
customer.accno=578599;
Think about the idea that some one can get to use our remote control and change our data. This leads to serious security concerns.
So how exactly to protect and hide our data is what ENCAPSULATION provides.
NOTE:
This is done by private modifiers i.e. declare your instance variables as private and allow the access to these variables through public setter and getter methods.
It is a thumb rule that the instance variables should be private for achieving Encapsulation.
public class Customer { /** * Encapsulating our instance variables by making them private. */ private int accNo; private String firstName; private String lastName; private String address; private int amount; private double mobileNo; /** * Creating public setter and getters for accessing the instance variable * */ public int getAccNo() { return accNo; } public void setAccNo(int accNo) { this.accNo = accNo; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public double getMobileNo() { return mobileNo; } public void setMobileNo(double mobileNo) { this.mobileNo = mobileNo; } void withdrawAmt() { System.out.println("Withdrawing Amount"); } void depositAmt() { System.out.println("Depositing Amount"); } /** * Main Method to test our Customer class */ public static void main(String args[]) { Customer customer = new Customer(); int verifyAccNo = 578598; /** * Using the dot operator we set the account Number */ customer.setAccNo(578598); if (customer.getAccNo() == verifyAccNo) { /** * Calling withdrawAmt() method of Customer */ customer.setAmount(5000); customer.withdrawAmt(); } } }
Inheritance:
Consider a scenario where you want to write code for some similar purpose. Take shapes as example. The figure below explains Inheritance:If you observe the above figure, we had 4 shapes, all of which did similar tasks of rotating and playing sound. If you code the above scenario you would have to write same methods in all 4 classes with very similar code. This is not a good programming practice.
NOTE:
To remove the above disadvantage of code duplication and facilitate the design to keep the similar objects performing similar tasks, we have Inheritance.When you design with Inheritance, you put common code in a class and then say to the more specific classes that the common (more abstract class) is their superclass. We say the subclass inherits (extends in terms of JAVA) from the superclass.
When we say subclass inherits from superclass, subclass not only inherits the methods but also the instance variables of the superclass.
If you again observe the figure the Amoeba Class, has rotate() which performs some specific task which is different from rest of the subclasses (This you can understand as amoeba would have some different way of rotating as it doesnot have a fixed shape as other other shapes), so some different logic is required for amoeba to rotate.
Thus, with Inheritance if some subclass performs more specifc task then we can do this by overriding the super class (also known as the base class) method. We say that amoeba overrides the inherited rotate() method.
public class Shape { private int width; private int height; private int area; public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getArea() { return area; } public void setArea(int area) { this.area = area; } public void rotate(){ System.out.println("Shape rotated"); } } /** * For indicating that a subclass inherits from the superclass we use extends keyword. * */ class Square extends Shape{ /** * Square class inherits all the instance variables and methods of the Shape Class. */ } class Circle extends Shape{ /** * Circle class also inherits all the instance variables and methods of the Shape Class. * But it has its own specific instance variable "radius", and an additional method, calcCircumference(). */ int radius; public void calcCircumference(){ System.out.println("Circumference calculated."); } } class Triangle extends Shape{ /** * Triangle class inherits all the instance variables and methods of the Shape Class. */ } class Amoeba extends Shape{ /** * Amoeba class inherits all the instance variables and methods of the Shape Class. * But it also overrides the inherited rotate() method to perform some specific task * which doesnot hold for other shapes. */ public void rotate(){ System.out.println("This is amoeba specific rotate()."); } }
Polymorphism:
Polymorphism means one thing having many forms.The above statement seems quite simple, now lets analyse this in more detail w.r.t to JAVA.
Consider the previously used example of shapes, you can create an object for a particular shape as follows:
If you see the above figure, this is the normal scenario of object creation.
Now what polymorphism provide is you can have something like below:
i.e. with polymorphism the reference type can be the super class of the actual object type.
How does this help:
You can make polymorphic arrays.
Shape[] shapes = new Shape[4]; shapes[0] = new Square(); shapes[1] = new Circle(); shapes[2] = new Triangle(); shapes[3] = new Amoeba(); for(int i=0; i<shapes.length; i++){ shapes[i].rotate(); }
The advantage is when i=0, square's rotate() method gets executed likewise for i=1, circle's rotate() method gets executed and so on. Now even if you add a new shape you do this with minimal impact on the code.
NOTE: The JVM on runtime decides what method to execute based on the object passed to the shape, as the decision to execute which object's method is taken at runtime, this type of polymorphism is called as runtime polymorphism also called method overriding as we saw in case of rotate() method of amoeba.
Another kind of polymorphism is Compile Time Polymorphism also called as Method Overloading :
This has nothing to do with Inheritance. This is just so that different methods of the same class has same method names, but the argument passed to each method is different.
public class Shape { static int calculateArea(int width, int height){ int area=width*height; return area; } static double calculateArea(int width, double height){ double area=0.5*width*height; System.out.println("Area of triangle is" + area ); return area; } static double calculateArea(int radius){ double area=Math.PI * Math.pow(radius, 2); System.out.println("Area of circle is" + area ); return area; } public static void main(String r[]){ double height=15; int width=10; int ht=5; int radius=7; /** * Now when we pass ht and width to calculate area i.e. both int * types * we get area of rectangle */ int areaSquare=calculateArea(width,ht); System.out.println("Area of rectange is " + areaSquare ); /** * Similarly when we pass height and width to calculate area i.e. * 1 int type * and 1 double type we get area of triangle */ double areaTriangle=calculateArea(width,height); System.out.println("Area of triangle is " + areaTriangle ); /** * Similarly for area of circle */ double areaCircle=calculateArea(radius); System.out.println("Area of circle is " + areaCircle ); } }
**More OOPS concepts coming Soon
Conclusion:
Please send in your suggestions in the comment section about the quality of the post. You can also request for any particular topic which you want me to put in. Your feedback is highly valuable.
Happy Programming!!




No comments:
Post a Comment