cs20 Java Module2
cs20 Java Module2
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or rectangle
etc.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
3)OOPs provides ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented
Programming language.
Name Convention
class name should start with uppercase letter and be a noun e.g. String, Color, Button,
System, Thread etc.
interface should start with uppercase letter and be an adjective e.g. Runnable, Remote,
name ActionListener etc.
method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(),
print(), println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
package should be in lowercase letter e.g. java, lang, sql, util etc.
name
constants should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY
name
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical (tengible and intengible). The example of
integible object is banking system.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state.
It is used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance(result) of a class.
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from
which objects are created.
o data member
o method
o constructor
o block
1. class Student1{
2. int id;//data member (also instance variable)
3. String name;//data member(also instance variable)
4. public static void main(String args[]){
5. Student1 s1=new Student1();//creating an object of Student
6. System.out.println(s1.id);
7. System.out.println(s1.name);
8. }
9. }
Output:0 null
Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
o Code Reusability
o Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
1. class Student2{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){ //method
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){System.out.println(rollno+" "+name);}//method
9. public static void main(String args[]){
10. Student2 s1=new Student2();
11. Student2 s2=new Student2();
12. s1.insertRecord(111,"Karan");
13. s2.insertRecord(222,"Aryan");
14. s1.displayInformation();
15. s2.displayInformation();
16.
17. }
18. }
Test it Now
111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference
variable refers to the object allocated in the Heap memory area. Here, s1 and s2 both
are reference variables that refer to the objects allocated in memory.
1. class Rectangle{
2. int length;
3. int width;
4. void insert(int l,int w){
5. length=l;
6. width=w;
7. }
8. void calculateArea(){System.out.println(length*width);}
9. public static void main(String args[]){
10. Rectangle r1=new Rectangle();
11. Rectangle r2=new Rectangle();
12. r1.insert(11,5);
13. r2.insert(3,15);
14. r1.calculateArea();
15. r2.calculateArea();
16. }
17. }
Output:55
45
Different ways to create an object in Java
There are many ways to create an object in java. They are:
o By new keyword
o By newInstance() method
o By clone() method
Annonymous object
Annonymous simply means nameless.An object that have no reference is known as
annonymous object.
If you have to use an object only once, annonymous object is a good approach.
1. class Calculation{
2. void fact(int n){
3. int fact=1;
4. for(int i=1;i<=n;i++){
5. fact=fact*i;
6. }
7. System.out.println("factorial is "+fact);
8. }
9. public static void main(String args[]){
10. new Calculation().fact(5);//calling method with annonymous object
11. }
12. }
Output:Factorial is 120
1. class Rectangle{
2. int length;
3. int width;
4. void insert(int l,int w){
5. length=l;
6. width=w;
7. }
8. void calculateArea(){System.out.println(length*width);}
9. public static void main(String args[]){
10. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
11. r1.insert(11,5);
12. r2.insert(3,15);
13. r1.calculateArea();
14. r2.calculateArea();
15. }
16. }
Output:55
45
Method Overloading in Java
Different ways to overload the method
By changing the no. of arguments
By changing the datatype
If a class have multiple methods by same name but different parameters, it is known as Method
Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b (int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand the
behavior of the method because its name differs. So, we perform method overloading to figure
out the program quickly.
java method overloading
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
By changing number of arguments
By changing the data type
In java, Method Overloading is not possible by changing the return type of the method.
1) Example of Method Overloading by changing the no. of arguments
In this example, we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Output:30
40
2) Example of Method Overloading by changing data type of argument
In this example, we have created two overloaded methods that differs in data type. The first sum
method receives two integer arguments and second sum method receives two double arguments.
class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
public static void main(String args[]){
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
Output:21.0
40
In java, method overloading is not possible by changing the return type of the method because
there may occur ambiguity. Let's see how ambiguity may occur: because there was problem:
class Calculation3{
int sum(int a,int b){System.out.println(a+b);}
double sum(int a,int b){System.out.println(a+b);}
public static void main(String args[]){
Calculation3 obj=new Calculation3();
int result=obj.sum(20,20); //Compile Time Error
}
}
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
Main overloading
class Overloading1{
public static void main(int a){
System.out.println(a);
}
public static void main(String args[]){
System.out.println("main() method invoked");
main(10);
}
}
Output:main() method invoked
10
Method Overloading and Type Promotion
One type is promoted to another implicitly if no matching datatype is found. Let's understand the
concept by the figure given below:
Method overloading with type promotion
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The
short datatype can be promoted to int,long,float or double. The char datatype can be promoted to
int,long,float or double and so on.
Example of Method Overloading with TypePromotion
class OverloadingCalculation1{
void sum(int a,long b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[]){
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
}
}
Output:40 60
Example of Method Overloading with Type Promotion if matching found
If there are matching type arguments in the method, type promotion is not performed.
class OverloadingCalculation2{
void sum(int a,int b)
{
System.out.println("int arg method invoked");
}
void sum(long a,long b)
{
System.out.println("long arg method invoked");
}
public static void main(String args[]){
OverloadingCalculation2 obj=new OverloadingCalculation2();
obj.sum(20,20);//now int arg sum() method gets invoked
}
}
Output:int arg method invoked
Example of Method Overloading with Type Promotion in case of ambiguity
If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.
class OverloadingCalculation3{
void sum(int a,long b){System.out.println("a method invoked");}
void sum(long a,int b){System.out.println("b method invoked");}
public static void main(String args[]){
OverloadingCalculation3 obj=new OverloadingCalculation3();
obj.sum(20,20);//now ambiguity
}
}
Output:Compile Time Error
Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
1. class Bike1{
2. Bike1(){System.out.println("Bike is created");}
3. public static void main(String args[]){
4. Bike1 b=new Bike1();
5. }
6. }
Output:
Bike is created
Default constructor provides the default values to the object like 0, null etc. depending
on the type.
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor.Here 0 and null values are provided by default
constructor.
1. class Student4{
2. int id;
3. String name;
4. Student4(int i,String n){
5. id = i;
6. name = n;
7. }
8. void display(){System.out.println(id+" "+name);}
9. public static void main(String args[]){
10. Student4 s1 = new Student4(111,"Karan");
11. Student4 s2 = new Student4(222,"Aryan");
12. s1.display();
13. s2.display();
14. }
15. }
Output:
Output:
There are many ways to copy the values of one object into another in java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using java
constructor.
1. class Student6{
2. int id;
3. String name;
4. Student6(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student6(Student6 s){
9. id = s.id;
10. name =s.name;
11. }
12. void display(){System.out.println(id+" "+name);}
13. public static void main(String args[]){
14. Student6 s1 = new Student6(111,"Karan");
15. Student6 s2 = new Student6(s1);
16. s1.display();
17. s2.display();
18. }
19. }
Output:
1. class Student7{
2. int id;
3. String name;
4. Student7(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student7(){}
9. void display(){System.out.println(id+" "+name);}
10. public static void main(String args[]){
11. Student7 s1 = new Student7(111,"Karan");
12. Student7 s2 = new Student7();
13. s2.id=s1.id;
14. s2.name=s1.name;
15. s1.display();
16. s2.display();
17. }
18. }
Output:
111 Karan
111 Karan
The access modifiers in java specify accessibility (scope) of a data member, method, constructor
or class.
Private
Default
Protected
Public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class, so
there is compile time error.
class A{
A obj=new A();
class A{
If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible
only within package.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
package pack;
class A{
void msg(){System.out.println("Hello");}
package mypack;
import pack.*;
class B{
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.
package pack;
public class A{
package mypack;
import pack.*;
class B extends A{
obj.msg();
Output:Hello
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
package pack;
public class A{
package mypack;
import pack.*;
class B{
obj.msg();
Output:Hello
Access Modifier within class within package outside package by subclass only
outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more
restrictive.
class A{
obj.msg();
The default modifier is more restrictive than protected. That is why there is compile time error.