OOP Through Java - UNIT-2
OOP Through Java - UNIT-2
Class
A class is a collection of member data and member functions (OR)
A class is a group of similar objects. It is a template or blueprint from which objects are
created.
A class in java can contain:
– member data
– member method/functions
– constructor
– block
– class and interface
Object
An runtime entity that have state and behavior is called as object.
Ex: Chair, TV, table, pen, etc..
Characteristics of Object:
– State : represents the data of an object. (value)
– Behavior : represents the behavior of an object (Functionality)
– Identity: Object identity is typically implemented via a unique ID.
Example:
pen is an object
color is white etc., known as state,
Used for writing is its behavior,
name is Reynolds.
Object is instance of the class. Class is a template or blueprint from which objects are created.
Syntax of class:
class classname
{
type instance-variable1;
Page1
Unit2: Classes, Methods, Constructors and Strings
type instance-variable2;
//....
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Program
public class sample
{
int x = 0;
int y = 0;
void display()
{
System.out.println(x+ " " + y);
}
Page2
Unit2: Classes, Methods, Constructors and Strings
This is the most popular way to create an object in Java. A new operator is also followed by a call
to constructor which initializes the new object. While we create an object it occupies space in the
heap.
Syntax
class_name object_name = new class_name()
Program 1
public class A
{
String str="hello";
public static void main(String args[])
{
A a1=new A(); //creating object using new keyword
System.out.println(a1.str);
}
}
2) Clone method
3) Anonymous Object
Anonymous means nameless. An object that have no reference is known as anonymous object. If
you want to use the object only once, anonymous object is a good approach.
Program
class Calculation
{
void fact(int n)
{
int fact=1;
for(inti=1;i<=n;i++)
{
fact=fact*i;
}
Page3
Unit2: Classes, Methods, Constructors and Strings
System.out.println("factorial is"+fact);
}
public static void main(String args[])
{
new Calculation().fact(5);
}
}
Constructor
Constructor in java is a special type of method that is used to initialize the object automatically.
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.
Rules for creating java constructor
There are basically two rules defined for the constructor.
– Constructor name must be same as its class name
– Constructor must have no explicit return type even void
Default Constructor
A constructor that have no parameter is known as default constructor.
Purpose:
– Default constructor provides the default values to the object like 0, null etc. depending on
the type.
Syntax of default constructor: <class_name>(){}
Program
class sample
{
int x;
int y;
sample() //constructor of class
{
x = 10;
y = 20;
}
void display()
{
System.out.println( x + " " + y);
Page4
Unit2: Classes, Methods, Constructors and Strings
}
}
class sampledemo
{
public static void main(String args[])
{
sample s1 = new sample(); // constructor will be call automatically from here
s1.display();
}
}
Parameterized Constructor
A constructor that have parameters is known as parameterized constructor.
Purpose:
– Parameterized constructor provides the values at runtime when the object is created
depending on the type.
Syntax of default constructor: <class_name>(datatype parameter1,….){}
Program
import java.util.Scanner;
class sample
{
int x,y;
sample(int a,int b) //constructor of class
{
x = a;
y = b;
}
void display()
{
System.out.println( x + " " + y);
}
}
class sampledemo
{
public static void main(String args[])
{
sample s1 = new sample(10,20); // constructor will be call automatically from here
s1.display();
}
}
This Keyword
In java, this is a reference variable that refers to the currently calling object.
Usage of java this keyword (4 usage of java this keyword)
– this keyword can be used to refer current class instance variable.
Page5
Unit2: Classes, Methods, Constructors and Strings
– this() can be used to invoke current class constructor.
– this keyword can be used to invoke current class method (implicitly)
– this can be passed as an argument in the method call.
class student
{
int id;
String name;
student(int id, String name)
{
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
student s1 = new student(101, "srk");
student s2 = new student(102, "lbrce");
s1.display();
s2.display();
}
}
class Student{
int id;
String name;
Student()
{
System.out.println("default constructor is invoked");
}
void display(){
Page6
Unit2: Classes, Methods, Constructors and Strings
System.out.println(id+" "+name);
}
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
Page7
Unit2: Classes, Methods, Constructors and Strings
Method Overloading
Class have multiple methods with same name but different parameters and definitions, it is
known as Method Overloading.
Advantage of method overloading
– It increases the readability of the program.
Different ways to overload the method:
– By Changing number of arguments
– By changing the data type
Program1
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);
}
}
Program2
class Calculation
{
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[])
{
Calculation obj=new Calculation();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
Page8
Unit2: Classes, Methods, Constructors and Strings
p1.display();
}
}
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.
Program
class Student{
int id;
String name;
int age;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}
Page9
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Constructor Vs Method
Pass by Reference: In the pass by reference concept, the method is called using an alias or reference of the actual
parameter. So, it is called pass by reference. It forwards the unique identifier of the object to the method. In this
formal parameters will affect the actual parameters.
Program:
class cbr
{
int a,b;
void getdata(int x, int y)
{
a=x;
b=y;
}
void swap(cbr c1)
{
int t;
t=c1.a;
c1.a=c1.b;
c1.b=t;
}
public static void main(String args[])
{
cbr c1=new cbr();
c1.getdata(10,20);
System.out.println("Before Swapping ");
System.out.println(c1.a+" "+c1.b);
c1.swap(c1);
System.out.println("After Swapping ");
System.out.println(c1.a+" "+c1.b);
}
}
Program
//Add two times and display information in proper time format
classTime
{
privateint hours,mins,secs;
Time()//Constructor with no parameter
Page11
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
{
hours = mins = secs =0;
}
Time(inthh,int m,intss)//Constructor with 3 parameters
{
hours =hh;
mins = m;
secs =ss;
}
Timeadd(Time tt2)
{
TimeTemp=newTime();
Temp.secs= secs + tt2.secs ;//add seconds
Temp.mins= mins + tt2.mins; //add minutes
Temp.hours= hours + tt2.hours;//add hours
if(Temp.secs>59) //seconds overflow check
{
Temp.secs=Temp.secs-60;//adjustment of minutes
Temp.hours++;//carry hour
}
returnTemp;
}
void display()
{
System.out.println(hours +" : "+ mins +" : "+ secs);
}
}
classReturningObjectsfromMethods
{
publicstaticvoid main(String[]args)
{
Time t1 =newTime(4,58,55);
Time t2 =newTime(3,20,10);
Time t3;
t3 = t1.add(t2);
System.out.print("Time after addition (hh:min:ss) ---->");
t3.display();
}
}
Recursion
Recursion is a process in which a method calls itself continuously. A method in java that calls itself is
called recursive method.
Page12
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Syntax
returntype methodname(){
//code to be executed
methodname();//calling same method
}
Program
Java inner class or nested class is a class that is declared inside the class or interface. (OR) class inside
a class or interface.
We use inner classes to logically group classes and interfaces in one place to be more readable and
maintainable.
Additionally, it can access all the members of the outer class, including private data members and
methods.
Syntax
class Java_Outer_class{
//code
class Java_Inner_class{
Page13
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
//code
}
}
There are two types of nested classes non-static and static nested classes. The non-static nested classes
are also known as inner classes.
Program
class outer{
private int data=30;
class inner{
void display(){
System.out.println("data is "+data);
}
}
public static void main(String args[]){
outer obj=new outer();
outer.inner in=obj.new inner();
in.display();
}
}
Output
Data is: 30
Page14
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
In simple words, a class that has no name is known as an anonymous inner class in Java. It should be
used if you have to override a method of class or interface. Java Anonymous inner class can be created in
two ways:
Program
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
Output
Nice fruits
A class i.e., created inside a method, is called local inner class in java. Local Inner Classes are the inner
classes that are defined inside a block. Generally, this block is a method body. If you want to invoke the
methods of the local inner class, you must instantiate this class inside the method.
Program
public class A{
private int data=30;//instance variable
void display(){
class B{
void msg(){System.out.println(data);}
Page15
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
}
B b1=new B();
b1.msg();
}
public static void main(String args[]){
A obj=new A();
obj.display();
}
}
Output
30
Static Keyword
class Student
Page16
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
{
int rollno;
String name;
static String college="ITS";
Student(int r, String n)
{
rollno = r;
name = n;
}
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Abinav");
Student s2 = new Student(222,"Harshitha");
s1.display();
s2.display();
}
}
Static Method
Program
class Student1
{
introllno;
String name;
static String college=“VITB";
static void change()
{
college = “VIT";
}
Student1(int r, String n)
{
rollno = r;
name = n;
}
Page17
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student1.change();
Student1 s1 = new Student1(111,"Abinav");
Student1 s2 = new Student1(222,"Harshitha");
Student1 s3 = new Student1(333,"Aadharsh");
s1.display();
s2.display();
s3.display();
}
}
Static Block
Static block is used to initialize the static data member.
It is executed before main method at the time of class loading
A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access
non-static data members and methods. It can be accessed by outer class name.
o It can access static data members of the outer class, including private.
o The static nested class cannot access non-static (instance) data members
Program1
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Page18
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Output
Data is 30
If you have the static member inside the static nested class, you don't need to create an instance of the
static nested class.
Program2
public class TestOuter2{
static int data=30;
static class Inner{
static void msg(){System.out.println("data is "+data);} }
public static void main(String args[]){
TestOuter2.Inner.msg();//no need to create the instance of static nested class
}
}
Output
Data is 30
The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an
input.
So, it provides a convenient way to check the behavior of the program for the different values. You can
pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Program
class cmddemo{
public static void main(String args[]){
int n=args.length();
for(i=0;i<n;i++)
System.out.println("Your"+i+" first argument is: "+args[i]);
}
}
Output
Page19
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
C:\>javac cmddemo.java
C:\>java cmddemo this is lbrce
Your 0 argument is: this
Your 1 argument is: is
Your 2 argument is: lbrce
Final Keyword
• The final keyword in java is used to restrict the user.
• The final keyword can be used in many context. Final can be:
– variable,
– method
– Class
• The final keyword can be applied with the variables, that have no value it is called blank final
variable.
• It can be initialized in the constructor only.
• The blank final variable can be static also which will be initialized in the static block only.
Final Variable
• If you make any variable as final, you cannot change the value of the final variable(it will be
constant).
Program
class fvdemo
{
final int speedlimit=90;
void run()
{
speedlimit=400;
}
Final Method
• If you make any method as final in super class, you cannot redefine it by its subclass.
Page20
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
class fmd
{
final void display()
{
System.out.println("Final method");
}
}
class fmddemo extends fmd
{
void display()
{
System.out.println("Final method");
}
public static void main(String args[])
{
fmddemo f1=new fmddemo();
f1.display();
}
}
Final class
• If you make any class as final, that cannot be inherited.
Access modifiers
in Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc to the user depending upon the access modifier used with
the element.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
5. Private protected
Examples:
String s1=”lbrce”;
String s2=new String(“Mylavaram”);
char x[]={‘a’, ’b’, ’c’, ’d’};
String s1=new String(x);
Page22
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Example: String s1=new String();
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a string”);
s1=sc.next();
NOTE: String objects are immutable objects. That means, once a value is assigned to a string object it
cannot be modified.
2.char charAt(int index): This method returns a character at a specified index value.
Example:
String s1=new String(“LBRCE”);
int n=s1.charAt(3);
4.boolean equals(String str): This method is used to check whether the two strings are identical or not.
This method returns true if strings are identical, otherwise returns false.
Example:
String s1=new String(“LBRCE”);
String s2=new String(“LBRCE”);
if(s1.equals(s2)) System.out.println(“equal”)
else System.out.println(“not equal”);
5.boolean equalsIgnoreCase(String str): This method is used to check whether the two strings are
identical or not by ignoring sensitive letters.
Page23
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Example
String s1=new String(“LBRCE”);
String s2=new String(“Lbrce”);
if(s1.equalsIgnoreCase(s2))
System.out.println(“equal”);
else System.out.println(“not equal”);
6.int indexOf(char ch): This method gives the index of first occurrence of given character in a string.
Example:
String s1=new String(“LakireddyBaliReddy College of Engineering”);
System.out.println(s1.indexOf(‘i’));
7.int lastIndexOf(char ch): This method returns the index of last occurrence of given character in a
string.
Example:
String s1=new String(“LakireddyBaliReddy College of Engineering”);
System.out.println(s1.lastIndexOf(‘i’)) ;
8.int indexOf(String str): This method returns the index of first occurrence of specified string in the
invoked string.
Example:
String s1=new String(“This is Java class”);
System.out.println(s1.indexOf(“is”));
9.int lastIndexOf(String str): This method returns the index of last occurrence of specified string in the
invoked string.
Example:
String s1=new String(“This is Java class”);
System.out.println(s1.indexOf(“is”));
10.boolean startsWith(String str): This method determines whether the invoking string starts with the
specified string or not.
This method returns true, if the invoking string starts with the specified string otherwise false.
Example:
String s1=new String(“This is Java class”);
System.out.println(s1.startsWith(“This”));
11.boolean endsWith(String str): This method determines whether the invoking string ends with the
specified string or not.
This method returns true, if the invoking string ends with the specified string otherwise false.
Example:
String s1=new String(“This is Java class”);
System.out.println(s1.endsWith(“Java”));
12.string substring(intstartindex): This method extracts a substring from the invoking string starting from
start index to till the end of the string.
Page24
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Example:
String s1=new String(“LakireddyBaliReddy College of Engineering”);
System.out.println(s1.substring(9));
13.string substring(intstartindex,intendindex): This method also extracts the substring from the invoking
string starting from start index to end index-1.
Example:
String s1=new String(“LakireddyBaliReddy College of Engineering”);
System.out.println(s1.substring(9,19));
14.int compareTo(string str): This method is used to compare two strings.This method returns integer
values such as positive or negative or zero value.
Return Value Meaning
<0 Invoking string is lesser than str
>0 Invoking string is greater than str
=0 Equal
Example:
String s1=”LBRCE”;
String s2=”Lbrce”;
System.out.println(s1.compareTo(s2));
15.int compareToIgnoreCase(String str): This method is used to compare the two strings by ignoring
case sensitive letters.
This method also gives integer values such as positive or negative or zero values.
Example:
String s1=”LBRCE”;
String s2=”Lbrce”;
System.out.println(s1.compareToIgnoreCase(s2));
16.string concat(String str): This method is used to concatenate the specified string with invoking string
and returns a string object.
Example:
String s1=”LBRCE”;
String s2=s1.concat(“college”);
System.out.println(s2);
17.string replace(char original,char replacement): This method is used to replace a character in a string
object with new character and returns a string object.
Example:
String s1=”hello”;
System.out.println(s1.replace(‘e’, ’a’));
18.string replace(string replace, string original): This method replaces a group of characters in a string
object with another group of characters and returns a string object.
Page25
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Example:
String s1=”lbrCE”;
System.out.println(s1.replace(“lbr”, “LBR”));
19.string join(charSequence delimiter, charSequence String): This method concatenates two or more
strings with specified delimiter.
Example:
String s1=new String();
System.out.println(s1.join(“ ”, ”This”, “is”, “Java”, “class”));
20.string toLowerCase(): This method is used to convert all the characters in the given string into
lowercase letters.
Example:
String s1=new String(“LBRCE”);
System.out.println(s1.toLowerCase());
21.string toUpperCase(): This method is used to convert all the characters in the given string into
uppercase letters.
Example:
String s1=new String(“lbrce”);
System.out.println(s1.toUpperCase());
22.string trim(): This method is used to remove any leading or trailing white spaces in the string object.
Example:
String s1=new String(“ LBRCE “);
System.out.println(s1.trim());
StringBuffer Class
String objects are always fixed length and are immutable objects.
In order to modify the string objects, we use StringBuffer class.
StringBuffer class provides string objects as growable and mutable objects.
StringBuffer class is one of the pre defined class in java.lang package.
StringBuffer class provides the following constructors.
1.StringBuffer(): This constructor is used to create StringBuffer object with capacity of 16 characters
without any reallocation.
Example:
StringBuffersb=new StringBuffer();
2.StringBuffer(int size): This constructor is used to create StringBuffer object with specified size as
capacity.
Example:
StringBuffersb=new StringBuffer(30);
3.StringBuffer(string str): This constructor is used to create StringBuffer object from string object and it
reserves 16 more characters without reallocation.
Example:
Page26
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
StringBuffersb=new StringBuffer(“hello”);
Methods
1.int length(): This method returns the length of the StringBuffer object.
Example:
StringBuffersb=new StringBuffer(“LBRCE”);
System.out.println(sb.length());
2.int capacity(): This method returns the capacity of the StringBuffer object.
Example:
StringBuffersb=new StringBuffer(“LBRCE”);
System.out.println(sb.capacity());
3.char charAt(int index): This method returns a character at a specified index value.
Example:
StringBuffersb=new StringBuffer(“Vishnu”);
int n=sb.charAt(5);
5.void setCharAt(intindex,charch) This method is used to set a new character at the specified index
value.
Example:
StringBuffersb=new StringBuffer(”hello”);
sb.setChar(1,’a’);
System.out.println(sb);
6.StringBuffer append(String str): This method is used to append the specified string to the invoking
StringBufferobject.
Example:
StringBuffersb=new StringBuffer(“Hello”);
sb.append(“ Java”);
System.out.println(sb);
7.StringBuffer append(intnum): This method appends string representation of integer type to the
StringBuffer object.
Example :
StringBuffersb=new StringBuffer(“hello”);
sb.append(123);
System.out.println(sb);
Page27
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
8.StringBuffer insert(int index, char ch): This method is used to insert a character at the specified index
value.
Example:
StringBuffersb=new StringBuffer(“hello”);
sb.insert(1,’a’);
System.out.println(sb);
9.StringBuffer insert(int index, string str): This method is used to insert a string in StringBuffer at the
specified index value.
Example:
StringBuffersb=new StringBuffer(“I Java”);
sb.insert(2,”like”);
System.out.println(sb);
10.StringBuffer reverse(): This method reverses all the characters in the invoking StringBuffer object.
Example:
StringBuffersb=new StringBuffer(“hello”);
sb.reverse();
System.out.println(sb);
12.StringBuffer delete(intstartindex, intendindex): This method deletes the characters from startindex to
endindex-1.
Example:
StringBuffersb=new StringBuffer(“hello JAVA”);
sb.delete(0,5); System.out.println(sb);
13.StringBuffer deleteCharAt(int index): This method deletes a single character available at the specified
index value.
Example: StringBuffersb=new StringBuffer(“hello JAVA”);
System.out.println(sb.deleteCharAt(4));
14.String substring(intstartindex): This method returns the subsequence from start index to end.
Example:
StringBuffersb=new StringBuffer(“stringbuffer”);
System.out.println(sb.substring(6));
15.String substring(intstartindex, intendindex): This method retirns the subsequence from start index to
end index exclusive.
Example:
Page28
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
StringBuffersb=new StringBuffer(“Hello this is a java program”);
System.out.println(sb.substring(6,20));
Programs
1. Write a program to check whether the given string is palindrome or not.
//Program to check the string is palindrome or not
import java.util.*;
class Palindrome {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
String s1=new String(); System.out.println(“Enter a string”);
s1=sc.next();
String s2=new String();
for(inti=s1.length()-1;i>=0;i--) {
s2=s2+s1.charAt(i);
}
if(s1.equals(s2))
System.out.println(“Given string is palindrome”);
else
System.out.println(“Given string is not a palindrome”);
}
}
Page29
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Page30