Remaining OOP's Concepts
Remaining OOP's Concepts
What is a constructor?
It is a special method, which has same name as class name and it doesn’t contain return type.
Types of constructors
class Emp {
int eno;
String ename;
float sal;
}
}
Output:
Object state
Eno: 1
Ename: Vishwa
Sal: 200000.0
Object state
Eno: 2
Ename: Harshan
Sal: 300000.0
Java compiler creates a default constructor for a class during compilation time. If that class doesn’t
contain any constructors.
This keyword
Note: we have to use this keyword to call same class constructor in another constructor except at the
time of object creation.
Ex:
One()
{
}
One(int a,int b){
this(); //calling non parameter constructo..
}
At the time of object creation we have to call constructor by using it’s name
Ex: new One();
Note: constructor calling statement must be the first statement in another constructor.
class One {
int a, b;
One(int a, int b) {
// a=100
// b=200
this.a = a;
this.b = b;
}
void display() {
System.out.println("Object state...");
System.out.println("a:\t" + a);
System.out.println("b:\t" + b);
}
}
class One {
int a, b;
One() {
System.out.println("Non parameterized....");
}
One(int a, int b) {
this();
System.out.println("Parameterized....");
this.a = a;
this.b = b;
}
void display() {
System.out.println("Object state...");
System.out.println("a:\t" + a);
System.out.println("b:\t" + b);
}
}
Encapsulation
Wrapping up of data (fields) and methods into a single unit is called as encapsulation.
Data Abstraction
Process of hiding un-necessary details and providing necessary details to the end-user is called as data
abstraction.
class Student {
int m1, m2, m3;
}
public class DataAbstraction {
public static void main(String[] args) {
Student s1 = new Student(99, 98, 100);
System.out.println("Is Pass:\t" + s1.isPass());
System.out.println("Grade:\t" + s1.getGrade());
}
}
Polymorphism
Method overloading
We can write more than one method with same name with different signature in a class. it is called as
method overloading.
Method signature
Method name along with parameter count, type and order is called as method signature
If we write more than one constructor in a class with different signature it is called as constructor
overloading.