Java is a platform independent web based application development platform.
Object Oriented Programming Concepts:
Polymorphism:
Java does not support Operator overloading explicitly.
Java does not support compile tome Polymorphism.
Function Overloading:
Function overloading says, we can have more than one function with the
same name in a class having different prototype.
5 things are there in function prototype:
1)
Access specifier e.g. public, private
2)
Access modifier e.g. static
3)
Return type e.g. void, int, Integer, String
4)
Function name e.g. main()
5)
Arguments e.g. main (String args[])
Only function name and arguments play role in function overloading.
1) change the number of arguments in each function:-
void show ()
void show (int)
void show (int, char, float)
void show (int, char)
2) If we want that the number of arguments should be same in each
function and still we want to achieve the function overloading, then change the
data types of their arguments:
void show (char
ch)
void shop (long l)
void show (byte b)
void show(int i)
“this” concept:
Whole OOPS is based on “this” concept. It always point to the current
object.
It is a reference variable which holds the reference of current object.
“this” is in built in java.
Note – it does not hold the address of object because in java we only
have reference not address. There is no explicit pointer concept in java we do
have it in c or c++.
Need of “this”: let’s take an
example to understand the need of “this”:
public class Student
{
int x = 10;
void show(int y)
{
System.out.println("x=" + x + ", y=" + y);
}
public static void main(String args[])
{
Student student =
new Student();
student.show(20);
}
}
Rule:
Whenever a class level variable and local variables are having a same
name, this scenario is known as data shadowing.
Now, change above class as below
and replace y with :
void show(int x)
{
System.out.println(x);
System.out.println(x);
}
Output:10, 10
Because priority always goes to the local variables e.g. if we have anything in our home itself then we never go to the shop to buy the new one.
In above example the local variable x acts as a shadow of instance
variable x. now, we want to print instance variable x also.
The alternate option is to pass the student object to show() method and
use it. Implicitly every objects are sent to the method in each non static
function.
If we have created an object and we want to access it then we must have
its reference id. “this” is something which holds the reference of current
object. So, System.out.println(x) is internally treated as
System.out.println(this.x) if x is instance variable. But in case of data
shadowing we must have to use “this” explicitly like this.x in order to access
the instance variable.
“this” keyword cannot be used in static methods because there is no
object involved in accessing static methods. Java does not pass any reference
id to the static methods. “this” are local always.
No comments:
Post a Comment