UNIT-2 OOP Lecture Notes
UNIT-2 OOP Lecture Notes
❖ Method Overloading:
✓ Overloading allows different methods to have the same name, but different
signatures where the signature can differ by the number of input parameters
or type of input parameters or both.
✓ Overloading is related to compile-time (or static) polymorphism.
✓ Method overloading increases the readability of the program.
1. class Adder{
2. static int add(int a,int b){
3. return a+b;}
4. static int add(int a,int b,int c){
5. return a+b+c;}
6. }
7. class TestOverloading1{ Output:
8. public static void main(String[] args){ 22
9. System.out.println(Adder.add(11,11)); 33
10. System.out.println(Adder.add(11,11,11));
11.}}
1. class Adder{
2. static int add(int a, int b){
3. return a+b;}
4. static double add(double a, double b){
5. return a+b;}
6. }
7. class TestOverloading2{
8. public static void main(String[] args){
9. System.out.println(Adder.add(11,11));
Output:
10. System.out.println(Adder.add(12.3,12.6));
11.}} 22
Note-1: 24.9
4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11)); //ambiguity }}
1. class TestOverloading4{
2. public static void main(String[] args){
3. System.out.println("main with String[]");}
4. public static void main(String args){ Output:t
5. System.out.println("main with String");} main with String[]
6. public static void main(){
7. System.out.println("main without args");} }
✓ If there are matching type arguments in the method, type promotion is not
performed.
1. class OverloadingCalculation2{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4. public static void main(String args[]){
5. OverloadingCalculation2 obj=new OverloadingCalculation2();
6. obj.sum(20,20); //now int arg sum() method gets invoked
7. } }
1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4. public static void main(String args[]){
5. OverloadingCalculation3 obj=new OverloadingCalculation3();
6. obj.sum(20,20); //now ambiguity Output:t
7. }
8. } Compile Time Error
❖ Constructor Overloading:
✓ In Java, we can overload constructors like methods.
✓ The constructor overloading can be defined as the concept of having more
than one constructor with different parameters so that every constructor can
perform a different task.
✓ Consider the following Java program, in which we have used different
constructors in the class.
Example
10. }
11. // Constructor 2 Output:t
12. Student(int id, String name){ Printing Student Information:
13. this("9899234455", "IIT Kanpur", 2018);
14. this.id = id; Name: John
15. this.name = name; Id: 101
16. } Contact No.: 9899234455
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output: 0 null 0.0
0 null 0.0
✓ In the above example, parameters (formal arguments) and instance variables are
same. So, we are using this keyword to distinguish local variable and instance
variable.
Solution of the above problem by this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output: 111 ankit 5000.0
112 sumit 6000.0
Note: If local variables (formal arguments) and instance variables are different,
there is no need to use this keyword.
2) this: to invoke current class method
✓ You may invoke the method of the current class by using the “this” keyword.
✓ If you do not use this keyword, compiler automatically adds this keyword while
invoking the method. Let us see the example
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
this.m(); //same as m() }
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n(); }}
Output: hello n
hello m
3) this() : to invoke current class constructor
✓ The this() constructor call can be used to invoke the current class constructor.
✓ It is used to reuse the constructor. In other words, it is used for constructor
chaining. Calling default constructor from parameterized constructor is follows.
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x); } }
class TestThis5{
public static void main(String args[]){
A a=new A(10); }}
Output: hello a
10
From the method side, a reference of type Foo with a name a is declared and it is
initially assigned to null.
boolean equalTo(ObjectPassDemo o);
As we call the method equalTo, the reference ‘o’ will be assigned to the object,
which is passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as the following
statement execute.
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to
‘ob2’. Since values of ‘a’ and ‘b’ are same for both the references, so
if(condition) is true, so boolean true will be return.
if(o.a == a && o.b == b)
Again ‘o’ will reassign to ‘ob3’ as the following statement execute.
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
Now as we can see, the equalTo method is called on ‘ob1’ , and ‘o’ is referring to
‘ob3’. Since values of ‘a’ and ‘b’ are not the same for both the references, so
if(condition) is false, so else block will execute, and false will be returned.
❖ Returning Objects
✓ In java, a method can return any type of data, including objects.
✓ For example, in the following program, the incrByTen( ) method returns an
object in which the value of an (an integer variable) is ten greater than it is in
the invoking object.
Example:
// Java Program to Demonstrate Returning of Objects
class ObjectReturnDemo {
int a;
// Constructor
ObjectReturnDemo(int i) { a = i; }
ob2 = ob1.incrByTen();
❖ Recursion in Java
✓ Recursion in java is a process in which a method calls itself continuously.
✓ A method in java that calls itself is called recursive method.
Java Recursion Example 1: Factorial Number
1. public class RecursionExample3 {
2. static int factorial(int n){ if (n == 1) return 1;
3. else return(n * factorial(n-1));
4. }
5. public static void main(String[] args)
6. { System.out.println("Factorial of 5 is: "+factorial(5));
7. } }
Output: Factorial of 5 is: 120
❖ Access Control
Access Modifiers in java:
✓ There are two types of modifiers in java: access modifiers and non-access
modifiers.
✓ The access modifiers in java specifies accessibility (scope) of a data member,
method, constructor, or class.
✓ There are 4 types of java access modifiers:
1. private access modifier:
✓ The private access modifier is accessible only within class.
Simple example of private access modifier
✓ 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.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();
8. System.out.println(obj.data);//Compile Time Error
9. obj.msg();//Compile Time Error
10. } }
2) default access modifier
✓ If you do not use any modifier, it is treated as default by default. The default
modifier is accessible only within package.
✓ Example of default access modifier
✓ 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.
//save by A.java
1. package pack;
2. class A{
3. void msg(){System.out.println("Hello");}
4. }
//save by B.java
5. package mypack;
6. import pack.*;
7. class B{
8. public static void main(String args[]){
9. A obj = new A();//Compile Time Error
10. obj.msg();//Compile Time Error
11. } }
✓ In the above example, the scope of class A and its method msg() is default so it
cannot be accessed from outside the package.
3) protected access modifier
✓ The protected access modifier is accessible within package and outside the
package but through inheritance only.
✓ The protected access modifier can be applied on the data member, method, and
constructor. It cannot be applied on the class.
Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}
✓ As with class methods and variables, a static nested class is associated with its
outer class.
✓ And like static class methods, a static nested class cannot refer directly to
instance variables or methods defined in its enclosing class: it can use them
only through an object reference.
✓ They are accessed using the enclosing class name.
OuterClass.StaticNestedClass
✓ For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =new OuterClass.StaticNestedClass();
Example:
// Java program to demonstrate accessing a static nested class
// outer class
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
}
}
}
// Driver class
public class StaticNestedClassDemo
{
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClas nestedObject = new OuterClass.StaticNestedClass();
nestedObject.display();
}
}
Inner classes
✓ To instantiate an inner class, you must first instantiate the outer class. Then,
create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
There are two special kinds of inner classes :
1. Local inner classes
2. Anonymous inner classes
Example:
// Java program to demonstrate accessing a inner class
// outer class
class OuterClass
{
static int outer_x = 10; // static member
int outer_y = 20; // instance(non-static) member
private int outer_private = 30; // private member
class InnerClass // inner class
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
// can also access non-static member of outer class
System.out.println("outer_y = " + outer_y);
// can also access a private member of the outer class
System.out.println("outer_private = " + outer_private);
}
}
}
public class InnerClassDemo
{
public static void main(String[] args) {
// accessing an inner class
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
innerObject.display(); }
}
Anonymous Inner Class in Java
✓ It is an inner class without a name and for which only a single object is created.
Syntax:
// Test can be interface, abstract/concrete class
Test t = new Test()
{
// data members and methods
public void test_method()
{
........
........
}
};
✓ The Java final keyword can be used in many contexts. Final can be:
variable, method, and class.
✓ There is a final variable speedlimit, we are going to change the value of this
variable, but It cannot be changed because final variable once assigned a
value can never be changed.
1. class Bike9{
2. final int speedlimit=90; //final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
Output:t
7. Bike9 obj=new Bike9();
8. obj.run(); Compile Time Error
9. } } //end of class
✓ The final keyword can be applied with the variables, a final variable that
have no value it is called blank final variable or uninitialized final
variable.
✓ Yes, we can initialize blank final variable but, in the constructor, only.
Example:
1. class Bike10{
2. final int speedlimit; //blank final variable
3. Bike10(){
4. speedlimit=70;
5. System.out.println(speedlimit); }
6.
7. public static void main(String args[]){ Output:t
8. Bike10 obj1 = new Bike10();
70
9. } }
Example:
Output:t
1. class A{
2. static final int data; //static blank final variable 50
3. static{ data=50;}
4. public static void main(String args[]){
5. System.out.println(A.data);
6. } }
2) Java final method: If you make any method as final, you cannot override it.
Example:
1. class Bike{
2. final void run(){
3. System.out.println("running");}
4. }
5. class Honda extends Bike{
6. void run(){
7. System.out.println("running safely with 100kmph");}
8. public static void main(String args[]){
9. Honda honda= new Honda(); Output:t
10. honda.run();
Compile Time Error
11. } }
3) Java final class: If you make any class as final, you cannot extend it.
Example:
Is final method inherited? Yes, final method is inherited but you cannot
override it.
Example:
1. class Bike{
2. final void run(){
3. System.out.println("running...");}
4. } Output:t
5. class Honda2 extends Bike{
6. public static void main(String args[]){ running….
7. new Honda2().run();
8. } }
❖ static Keyword
✓ The static keyword in Java is used for memory management mainly.
✓ We can apply static keyword with variables, methods, blocks and nested
classes. The static keyword belongs to the class than an instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
1. class Student{
2. int rollno;//instance variable
3. String name;
4. static String college ="ITS";//static variable
5. //constructor
6. Student(int r, String n){
7. rollno = r;
8. name = n;
9. }
10. void display (){System.out.println(rollno+" "+name+" "+college);}
11. }
12. //Test class to show the values of objects
13. public class TestStaticVariable1{
14. public static void main(String args[]){
15. Student s1 = new Student(111,"Karan");
16. Student s2 = new Student(222,"Aryan");
17. //we can change the college of all objects by the single line of code
18. //Student.college="BBDIT";
19. s1.display(); Output:t
20. s2.display(); 111 Karan ITS
21. } 222 Aryan ITS
22. }
1. class Student{
2. int rollno;
3. String name;
4. static String college = "ITS";
5. //static method to change the value of static variable
6. static void change(){
7. college = "BBDIT";
8. }
9. //constructor to initialize the variable
10. Student(int r, String n){
11. rollno = r;
12. name = n;
13. }
14. void display(){System.out.println(rollno+" "+name+" "+college);}
15. }
16. //Test class to create and display the values of object
17. public class TestStaticMethod{
18. public static void main(String args[]){
19. Student.change();//calling change method
20. //creating objects
21. Student s1 = new Student(111,"Karan");
22. Student s2 = new Student(222,"Aryan");
23. Student s3 = new Student(333,"Sonoo");
24. //calling display method Output:t
25. s1.display();
26. s2.display(); 111 Karan BBDIT
222 Aryan BBDIT
27. s3.display();
333 Sonoo BBDIT
28. } }
3) Java static block
1. class A2{
2. static{System.out.println("static block is invoked");} Output:t
3. public static void main(String args[]){ static block is invoked
4. System.out.println("Hello main"); Hello main
5. } }
✓ Inheritance helps in reducing the overall code size of the program, which is
an important concept in object-oriented programming.
Implementing inheritance in Java: For creating a sub-class which is inherited
from the base class follow the below syntax.
Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
✓ subclass_name is the name of the sub class,
✓ extends keyword indicates that you are making a new class that derives
from an existing class.
✓ superclass_name is the name of the base class from which you want to
inherit the sub class.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
1. class Animal{
2. void eat(){System.out.println("eating...");} }
3. class Dog extends Animal{
4. void bark(){System.out.println("barking...");} }
5. class Cat extends Animal{
6. void meow(){System.out.println("meowing...");} }
7. class TestInheritance3{
8. public static void main(String args[]){
9. Cat c=new Cat();
10. c.meow(); Output:
11. c.eat(); meowing
eating...
Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 31
UNIT-2 – Object Oriented Programming
12. //c.bark();//C.T.Error
13.}}
1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color); //prints color of Dog class
8. System.out.println(super.color); //prints color of Animal class }
9. }
10. class TestSuper1{
11. public static void main(String args[]){ Output:t
12. Dog d=new Dog();
13. d.printColor(); black
14.}} white
✓ In the above example, Animal and Dog both classes have a common
property color.
✓ If we print color property, it will print the color of current class by default.
To access the parent property, we need to use super keyword.
2) super can be used to invoke parent class method.
✓ The super keyword can also be used to invoke parent class method.
✓ It should be used if subclass contains the same method as parent class.
✓ In other words, it is used if method is overridden.
Example:
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work() {
8. super.eat();
9. bark(); }
10.}
11. class TestSuper2{
12. public static void main(String args[]){ Output:t
eating…
Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE barking 33
UNIT-2 – Object Oriented Programming
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created"); }
8. } Output:t
9. class TestSuper3{
10. public static void main(String args[]){ animal is created
11. Dog d=new Dog(); }} dog is created
❖ Polymorphism in Java
✓ Polymorphism in Java is a concept by which we can perform a single action
in different ways.
✓ Polymorphism is derived from 2 Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So, polymorphism means
many forms.
✓ There are two types of polymorphism in Java: compile-time polymorphism
and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.
✓ If you overload a static method in Java, it is the example of compile time
polymorphism.
❖ Method Overriding:
✓ Overriding is a feature that allows a subclass or child class to provide a
specific implementation of a method that is already provided by one of its
super-classes or parent classes.
✓ When a method in a subclass has the same name, same parameters or
signature, and same return type(or sub-type) as a method in its super-class,
then the method in the subclass is said to override the method in the super-
class.
✓ If subclass (child class) has the same method as declared in the parent class,
it is known as method overriding in Java.
✓ Method overriding is used for runtime polymorphism
✓ When we call this overridden method, it will execute the method of the child
class, not the parent class.
method only.
Return type can be same or different in
method overloading. But you must have to
change the parameter.
❖ Runtime Polymorphism in Java
✓ Runtime polymorphism or Dynamic Method Dispatch is a process in which
a call to an overridden method is resolved at runtime rather than compile-
time.
✓ In this process, an overridden method is called through the reference
variable of a superclass.
✓ The determination of the method to be called is based on the object being
referred to by the reference variable.
Upcasting:
✓ If the reference variable of Parent class refers to the object of Child class, it
is known as upcasting.
3. System.out.println("running");}
4. }
5. class Splendor extends Bike{
6. void run(){
7. System.out.println("running safely with 60km");}
8. Output:t
9. public static void main(String args[]){
running safely with 60km.
10. Bike b = new Splendor(); //upcasting
11. b.run(); } }
1. class Bike{
2. int speedlimit=90; }
3. class Honda3 extends Bike{
4. int speedlimit=150;
5. public static void main(String args[]){
6. Bike obj=new Honda3();
7. System.out.println(obj.speedlimit); //90 }
Example:
1. class Animal{
2. void eat(){
3. System.out.println("animal is eating...");} }
4. class Dog extends Animal{
5. void eat(){
6. System.out.println("dog is eating...");} }
Output:t
Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE dog is eating... 39
UNIT-2 – Object Oriented Programming
✓ Since, BabyDog is not overriding the eat() method, so eat() method of Dog
class is invoked.
❖ Abstract class
✓ A class which is declared as abstract is known as an abstract class.
✓ Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
✓ Another way, it shows only essential things to the user and hides the internal
details.
✓ Abstraction lets you focus on what the object does instead of how it does it.
✓ In this example, Bike is an abstract class that contains only one abstract
method run. Its implementation is provided by the Honda subclass.
✓ An abstract class can have a data member, abstract method, method body
(non-abstract method), constructor, and even main() method.
✓ Rule: If you are extending an abstract class that has an abstract method, you
must either provide the implementation of the method or make this class
abstract.
20. obj.changeGear();
21. }
22. }
❖ Strings
✓ Strings, which are widely used in Java programming, are a sequence of
characters.
✓ In the Java programming language, strings are objects.
✓ The Java platform provides the String class to create and manipulate strings.
✓ Java String contains an immutable sequence of Unicode characters.
✓ Java String is differ from string in C or C++, where (in C or C++) string is
simply an array of characters.
✓ String class is encapsulated under java.lang package.
char[] ch={'j','a','v','a','p','r','o','g','r','a'.’m’,’m’,’i’,’n’,’g’};
String s=new String(ch);
Is same as String s="javaprogramming";
1. String literal
✓ In java, Strings can be created like this: Assigning a String literal to a String
instance:
String str1 = "Welcome";
String str2 = "Welcome";
✓ String is an object in Java. However, we have not created any string object
using new keyword above.
✓ The compiler does that task for us it creates a string object having the string
literal (that we have provided , in this case it is “Welcome”) and assigns it to
the provided string instances.
✓ But if the object already exist in the memory it does not create a new Object
rather it assigns the same old object to the new instance, that means even
though we have two string instances above(str1 and str2) compiler only
created on string object (having the value “Welcome”) and assigned the
same to both the instances.
✓ For example, there are 10 string instances that have same value, it means
that in memory there is only one object having the value and all the 10 string
instances would be pointing to the same object.
System.out.println(str2);
System.out.println(str3);
} }
To return String
valueOf() valueOf(char[] data) String representation of the
passed argument.
Example:
import java.lang.*;
public class Test_Strings {
public static void main(String args[]) {
result3 = s2.compareTo( s3 );
System.out.println(result3);
result3 = s3.compareTo( s1 );
System.out.println(result3);
System.out.println();
// boolean contentEquals(StringBuffer sb)
boolean result = str1.contentEquals( str2 );
System.out.println("Is Str1 and Str2 equals: "+result);
String str3 = new String( "Department of EEE, LBRCE");
boolean res2 = str1.contentEquals( str3 );
System.out.println("Is Str1 and Str3 equals: "+res2);
System.out.println();
// int indexOf(String str, int fromIndex)
String Str4 = new String("Welcome to Java Programming");
String SubStr1 = new String("Java" );
System.out.print("Found Index :" );
System.out.println( Str4.indexOf( SubStr1, 15 ));
// toCharArray()
System.out.print("Return Value :" );
System.out.println(Str4.toCharArray() );
// concat(String str)
String Str5 = "Strings are immutable";
Str5 = Str5.concat(" all the time");
System.out.println(Str5);
// replace(char oldChar, char newChar)
// strip() or trim()
String Str8 = new String(" Welcome to lbrce.com ");
System.out.print("Return Value :" );
System.out.println(Str8.trim() );
// String copyValueOf()
char[] Str1 = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
String Str2 = "";
Str2 = Str2.copyValueOf( Str1 );
System.out.println("Returned String: " + Str2);
}
}
❖ StringBuffer Class
✓ Java StringBuffer class is used to create mutable (modifiable) String objects.
✓ The StringBuffer class in Java is the same as String class except it is mutable
i.e. it can be changed.
Important Constructors of StringBuffer Class
✓ The capacity() method of the StringBuffer class returns the current capacity of
the buffer. The default capacity of the buffer is 16.
✓ If the number of character increases from its current capacity, it increases the
capacity by (oldcapacity*2)+2.
✓ For example if your current capacity is 16, it will be (16*2)+2=34.
1. class StringBufferExample6{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity()); //default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity()); //now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 [(oldcapacity*2)+ 2]
9. } }
❖ StringTokenizer
✓ The java.util.StringTokenizer class allows you to break a String into tokens. It
is simple way to break a String.
✓ In the StringTokenizer class, the delimiters can be provided at the time of
creation or one by one to the tokens.
Example:
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st1 = new StringTokenizer("Dept. of CSE LBRCE"," ");
// boolean hasMoreTokens()
while (st1.hasMoreTokens()) {
System.out.println(st1.nextToken()); }
System.out.println("");
System.out.println("");
// boolean hasMoreElements()
while (st3.hasMoreElements()) {
System.out.println(st3.nextToken()); }
System.out.println("");
// Object nextElement()
while (st4.hasMoreTokens()) {
System.out.println(st4.nextElement()); }
System.out.println("");
// int countTokens()