Java OOPs Concept, Constructors, PolyMorphism, Constructor Overloading, Static Keyword
Object Oriented Features
OOPs is a method of implementation where a co-operative collection of objects may be created, accessed and deployed.
Features:
- Classes and Objects
- Data Abstraction
- Data Encapsulation
- Polymorphism
- Inheritance
- Persistence
- Extendability
- Message Passing
Class
A class is a description of similar kind of objects or class is a blue print for several objects. A class is a logical entity that gives description of related objects.
Object
Object is a real world entity or An object is an instance of a class. An object is a physical entity which occupies certain space in memory.
Data Abstraction
It is a process of exhibiting the essential details by hiding the unwanted details on demand. It is a process of creating a new datatype called ADT [ Abstract Data Type].
Data Encapsulation
The process of wrapping up data and its methods into a single unit is nothing but encapsulation.
Poly Morphism
The ability to provide multiple definitions with same method signature.
Inheritance
The ability to extent the features of one class to another class is nothing but inheritance. The main Objective is code reusability.
Persistence
The process of making the object state permanent is nothing but persistence. The object by nature is temporary.
Extendibility
The ability to enhance the features or properties of the system without restructuring the existing system.
Message Passing
The process of invoking the method over an object is nothing but message passing.
An example program for demonstrating class and objects.
class Student{
private int stno,year;
private string name,branch; // method to set student details
public setStudent() {
stno = 1001;
name = "Raju";
branch = "CSE";
year = 2;
}
// method to display the student details
public void getStudent() {
System.out.println(stno+" "+name+" "+br+" "+year);
}
}
public class StudentDemo{
public static void main(String[] args) {
// create object s
Student s = new Student();
// set the student details
// calling method setStudent()
s.setStudent();
// displaying the student details
// calling method getStudent()
s.getStudent();
}
}
Output:
1001 Raju CSE 2
Constructors
A constructor is a special method that initializes an object of a class. Initialization is a process of assigning values to the data methods (or) instant variables of a class. Unless an object is initialized it cannot be kept in use.
A constructor initializes such objects when ever they are created. It is the first function to be executed when ever the object is created. It is executed only once and is invoked/implicitly called by the compiler.
The constructor must have the same name as its class name. Generally the constructor should be declared as public as it is meant for object initialization it doesn’t return any value. Even void should not be mentioned.
An example program for demonstrating Constructors
class Box{
private int height,width,depth;//Constructor
public Box(){
height=5;
width=4;
depth=3;
}//A method for setting height
public void setHeight(int h){
height=h;
}//A method for setting width
public void setWidth(int w){
width=w;
}//A method for setting depth
public void setDepth(int d){
depth=d;
}//A method for setting all the attributes
public void setBox(int h,int w,int d){
height=h;
depth=d;
width=w;
}//A method for getting height
public int getHeight(){
return height;
}//A method for getting width
public int getWidth(){
return width;
}//A method for getting depth
public int getDepth(){
return depth;
}//A method for getting volume
public int getVolume(){
return height*depth*width;
}}public class BoxDemo{
public static void main(String[] args) {
Box b = new Box();
System.out.println("Volume="+b.getVolume());
b.setBox(1,2,3);
System.out.println("Volume="+b.getVolume());
b.setHeight(10);
System.out.println("Volume="+b.getVolume());
b.setBox(12,22,23);
System.out.println("Volume="+b.getVolume());System.out.println("Displaying the values of Height, Width, Depth");
System.out.println(b.getHeight() + " "+b.getWidth()+" "+b.getDepth());}
}
Output:
Volume=60
Volume=6
Volume=60
Volume=6072
Displaying the values of Height, Width, Depth
12 22 23
Parameterized Constructors
A constructor that accepts data as an argument is a parameterized constructor.
class Box{
private int height,width,depth;//Constructor
public Box(int h,int w,int d){
height=h;
width=w;
depth=d;
}//A method for setting height
public void setHeight(int h){
height=h;
}//A method for setting width
public void setWidth(int w){
width=w;
}//A method for setting depth
public void setDepth(int d){
depth=d;
}//A method for setting all the attributes
public void setBox(int h,int w,int d){
height=h;
depth=d;
width=w;
}//A method for getting height
public int getHeight(){
return height;
}//A method for getting width
public int getWidth(){
return width;
}//A method for getting depth
public int getDepth(){
return depth;
}//A method for getting volume
public int getVolume(){
return height*depth*width;
}}public class BoxDemo{
public static void main(String[] args) {
Box b = new Box(1,2,3);
System.out.println("Volume="+b.getVolume());
b.setBox(1,2,3);
System.out.println("Volume="+b.getVolume());
b.setHeight(10);
System.out.println("Volume="+b.getVolume());
b.setBox(12,22,23);
System.out.println("Volume="+b.getVolume());System.out.println("Displaying the values of Height, Width, Depth");
System.out.println(b.getHeight() + " "+b.getWidth()+" "+b.getDepth());}
}
Output:
Volume=60
Volume=6
Volume=60
Volume=6072
Displaying the values of Height, Width, Depth
12 22 23
Static keyword
In a class either data or method can be declared as static.
- In case of data as static the variable becomes sharable among all the object of the class has only one instance of the static variable is created in the method.
- In case of method as static, it doesn’t use the object of a class. When a class doesn’t hold any data members then it is better to declare the method as static. A static method can be increased with the help of class name.
- A class method can have access to static data only.
class Account {
//define variables
private int accno;
private double balance; // balance for account
private double annualInterestRate; //stores the current interest rate
private static int minbal=500;//no arg construtor
Account () {
balance = 0.0;
annualInterestRate = 0.0;
}
//constructor with specific id and initial balanceAccount(int no, double newBalance) {
accno= no;
balance = newBalance;
}Account(int newno, double newBalance, double newAnnualInterestRate) {
accno= newno;
balance = newBalance;
annualInterestRate = newAnnualInterestRate;
}//accessor/mutator methods for accno, balance, and annualInterestRatepublic int getaccno() {
return accno;
}public double getBalance() {
return balance;
}public double getAnnualInterestRate() {
return annualInterestRate;
}public void setAccNo(int acc_no) {
accno= acc_no;
}public void setBalance(double newBalance) {
balance = newBalance;
}public void setAnnualInterestRate(double newAnnualInterestRate) {
annualInterestRate = newAnnualInterestRate;
}//define method getMonthlyInterestRate
double getMonthlyInterestRate() {
return annualInterestRate/12;
}//define method withdraw
double withdraw(double amount) {if((balance-amount)>minbal)
return balance -= amount;else
return 0;
}
//define method deposit
double deposit(double amount) {
return balance += amount;
}
public static void changeMinBalance(){
minbal+=1000;
System.out.println("Minimum Balance Changed");}public class StaticDemo{
public static void main(String[] args) {
Account account1 = new Account(1122, 20000, .045);
account1.withdraw(2500);
account1.deposit(3000);
System.out.println("Account No:" + account1.accno);
System.out.println("Balance:" + account1.getBalance());
System.out.println("Interest Rate:" + account1.getAnnualInterestRate());
System.out.println("Balance after withdraw of 2500:" + account1.getAnnualInterestRate());
System.out.println("Balance after deposit of 3000:" + account1.getAnnualInterestRate());
System.out.println("Monthly Interest:" + account1.accno);Account.changeMinBalance();//Static method call
System.out.println("Process completed.");
}
}
Output
Account No:1122
Balance:20500.0
Interest Rate:0.045
Balance after withdraw of 2500:0.045
Balance after deposit of 3000:0.045
Monthly Interest:1122
Minimum Balance Changed
Process completed.
Polymorphism
It is the ability to provide multiple definations to the same method signature.
Here poly means many and morphism means forms.
Advantages
Polymorphism is used to build complex software system where the methods that form similar activity can have the same name.
The compiler is able to discriminate one method with another based on arguments. To be more specific the number of arguments, type of arguments and order of arguments.
Syntax of a method:
A method signature doesn’t include returntype. Here some of the valid and invalid methods are given below.
/* File name : Employee.java */
public class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck() {
System.out.println("Mailing a check to " + this.name + " " + this.address);
}
public String toString() {
return name + " " + address + " " + number;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
Now suppose we extend Employee class as follows −
/* File name : Salary.java */
public class Salary extends Employee {
private double salary; // Annual salary
public Salary(String name, String address, int number, double salary) {
super(name, address, number);
setSalary(salary);
}
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if(newSalary >= 0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}
Now, you study the following program carefully and try to determine its output −
/* File name : VirtualDemo.java */
public class VirtualDemo {
public static void main(String [] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}
Output
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0
Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0
Here, we instantiate two Salary objects. One using a Salary reference s, and the other using an Employee reference e.
While invoking s.mailCheck(), the compiler sees mailCheck() in the Salary class at compile time, and the JVM invokes mailCheck() in the Salary class at run time.
mailCheck() on e is quite different because e is an Employee reference. When the compiler sees e.mailCheck(), the compiler sees the mailCheck() method in the Employee class.
Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time, however, the JVM invokes mailCheck() in the Salary class.
This behavior is referred to as virtual method invocation, and these methods are referred to as virtual methods. An overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time.
Constructor Overloading
As a constructor is also a mthod, it can also be overloaded.
If a class consists of multiple constructors it provides flexibility in creating objects for class.
// Java program to illustrate
// Constructor Overloadingclass Box{double width, height, depth;// constructor used when all dimensions specifiedBox(double w, double h, double d){width = w;
height = h;
depth = d;
}// constructor used when no dimensions specifiedBox(){
width = height = depth = 0;
}// constructor used when cube is created
Box(double len){
width = height = depth = len;}
// compute and return volumedouble volume(){
return width * height * depth;
}
}// Driver codepublic class Test{public static void main(String args[]){// create boxes using the various
// constructorsBox mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;// get volume of first box
vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);// get volume of second boxvol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);// get volume of cube
vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);}
}Output:Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0
Using this() in constructor overloading
this() reference can be used during constructor overloading to call default constructor implicitly from parameterized constructor. Please note, this() should be the first statement inside a constructor.