0% found this document useful (0 votes)
63 views70 pages

Unit 2 (Objects and Classes)

Uploaded by

Ridhi Aggarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views70 pages

Unit 2 (Objects and Classes)

Uploaded by

Ridhi Aggarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

Objects and Classes

Basics of objects and classes in java, Constructors, Finalizer, Visibility


modifiers, Methods and objects, Inbuilt classes like String, Character,
StringBuffer, File, this reference.
Basics of objects and classes
• Class: A class is the building block of object oriented programming.
It is User Defined Datatype (UDT) which has data & functions.
• Object: It is an instance of a Class i.e. variable of UDT.
Each object has its own
variables/functions
Characteristics of Object
State: represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
Identity: An object identity is typically implemented via a unique ID.
The value of the ID is not visible to the external user. However, it is
used internally by the JVM to identify each object uniquely.
Class is a logical entity. It can't be
physical.
• A class in Java can contain:
Fields
Methods
Constructors
Blocks
Nested class and interface
Object and Class Example: main within
the class
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//
accessing member through reference variable
System.out.println(s1.name);
}
}
Object and Class Example: main outside
the class
class Student{
int id;
String name;
}
//
Creating another class TestStudent1 which contains the main meth
od
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
3 Ways to initialize object

1. By reference variable
2. By method
3. By constructor
• Initialization through reference
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student(); //reference variable s1
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);
//printing members with a white space
}
}
• Initialization through method
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation()
{System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
Example class Employee{
int id; String name; float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display()
{System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e1.display();
e2.display();
}
}
Different ways to create an object
in Java
Anonymous object
• new Calculation(); //anonymous object
• Calculation c=new Calculation(); // Calling method through a reference
c.fact(5)
• new Calculation().fact(5); //Calling method through an anonymous object
Creating multiple objects by one type only
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//
creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Method
• A method is a block of code or collection of statements or a set of code
grouped together to perform a certain task or operation. The method is
executed only when we call or invoke it.
• The method declaration provides information about method attributes,
such as visibility, return-type, name, and arguments.
Access Specifier: Access specifier or modifier is the access type of the
method and specifies the visibility of the method. Java
provides four types of access specifier:

Public: The method is accessible by all classes when we use public


specifier in our application.
Private: When we use a private access specifier, the method is accessible
only in the classes in which it is defined.
Protected: When we use protected access specifier, the method is
accessible within the same package or subclasses in a different package.
Default: When we do not use any access specifier in the method
declaration, Java uses default access specifier by default. It is visible only
from the same package only.
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7)
);
}
}

//user defined method


public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
Static Method
• A method that belongs to a class rather than an instance of a
class.
• It can access static data members and also change the value of it.
• It is used to create an instance method.
• It is invoked by using the class name.
• The best example of a static method is the main() method.
Instance Method
public class InstanceMethodExample
{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExampl
e();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-
defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
• There are two types of instance method:
Accessor Method public int getId()
{
return Id;
}
Mutator Method

public void setRoll(int roll)


{
this.roll = roll;
}
Abstract Method
• The method that does not has method body (without an
implementation).
• It always declares in the abstract class.
• It means the class itself must be abstract if it has abstract method.
• To create an abstract method, use the keyword abstract.
abstract class Demo //abstract class
{
//abstract method declaration
abstract void display();
}
public class MyClass extends Demo
{
//method impelmentation
void display()
{
System.out.println("Abstract method?");
}
public static void main(String args[])
{
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
obj.display();
}
}
Constructors
• A constructor is a block of codes similar to the method. It is called
when an instance of the class is created.
• At the time of calling constructor, memory for the object is allocated
in the memory.
• It is a special type of method which is used to initialize the object.
• Every time an object is created using the new() keyword, at least one
constructor is called. It calls a default constructor if there is no
constructor available in the class.
• Two rules defined for the constructor are:
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized

• Two types:
Default constructor (no-arg constructor)
Parameterized constructor
Default vs Parameterized Constructor

class Bike1{ public static void main(String args[]){


//creating a default constructor //creating objects and passing values
Bike1(){System.out.println("Bike is created");} Student4 s1 = new Student4(111,"Karan
//main method ");
public static void main(String args[]){ Student4 s2 = new Student4(222,"Aryan
//calling a default constructor ");
Bike1 b=new Bike1(); //
} calling method to display the values of obje
} ct
s1.display();
s2.display();
}
Constructor Overloading in Java
class Student5{
int id;
String name; int age;
//creating two arg constructor
Student5(int i,String n){
id = i; name = n;
}
//creating three arg constructor
Student5(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[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display(); Difference between constructor and method in Ja
Java Copy Constructor
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i; name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id; name =s.name;
}
void display()
{System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
Copying values without constructor
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}

What is the purpose of Constructor class


static keyword
• static variable
The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
The static variable gets memory only once in the class area at the time of
class loading.
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display ()
{System.out.println(rollno+" "+name+" "+college);}
• static method
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an
instance of a class.
A static method can access static data member and can change the
value of it.
class Calculate{
static int cube(int x){
return x*x*x;
}

public static void main(String args[]){


int result=Calculate.cube(5);
System.out.println(result);
}
}
• static block
Is used to initialize the static data member.
It is executed before the main method at the time of classloading.

class A2{
static{System.out.println("static block is invo
ked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
this reference
1) this: to refer current class instance variable

• Understanding the problem without this keyword


class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display()
{System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
Solution of the problem is using 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 TestThis{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
2) this: to invoke current class method
3) this() : to invoke current class constructor
Calling default constructor from parameterized
constructor
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis{
public static void main(String args[]){
A a=new A(10);
}}
Calling parameterized constructor from default
constructor
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis{
public static void main(String args[]){
A a=new A();
}}
4) this: to pass as an argument in the
method
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();
}
}
5) this: to pass as argument in the
constructor call
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//
using data member of A4 class
}
}

class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
6) this keyword can be used to return
current class instance
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
final keyword
1) final with Variables: The value of variable cannot be changed once
initialized. if we modify it then we get Compile Time Error.
(2) final with Method: Whenever we declare any method as final, then it
means that we can’t override that method.
(3) final with Class: Whenever we declare any class as final, it means that
we can’t extend that class or we can’t make subclass of that class.
Program to illustrate final keyword
final class G {

// by default it is final.
void h() {}

// by default it is not final.


static int j = 30;

public static void main(String[] args)


{
// See modified contents of variable j.
j = 36;
System.out.println(j);
}
}
Inbuilt classes
(1) Java String
char[] ch={'j','a','v','a',‘p',‘r','o',‘g',‘r',‘a‘,‘m'};
String s=new String(ch);

is same as:

String s="javaprogram";
Two ways to create String object:

1. By string literal
String s="welcome";

String s1="Welcome";
String s2="Welcome"; //It doesn't create a new instance

2. By new keyword
String s=new String("Welcome"); //creates two objects and one reference variable
Example
public class StringExample{
public static void main(String args[]){
String s1="java"; //creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch); //converting char array to string
String s3=new String("example"); //creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Java String class methods
Method Description
char charAt(int index) It returns char value for the particular index
int length() It returns string length
static String format(String format, It returns a formatted string.
Object... args)
static String format(Locale l, String It returns formatted string with given locale.
format, Object... args)
String substring(int beginIndex) It returns substring for given begin index.
String substring(int beginIndex, int It returns substring for given begin index and
endIndex) end index.
boolean contains(CharSequence s) It returns true or false after matching the
sequence of char value.
static String join(CharSequence It returns a joined string.
delimiter, CharSequence... elements)
boolean equals(Object another) It checks the equality of string with the given
Method Description
boolean isEmpty() It checks if string is empty.
String concat(String str) It concatenates the specified string.
String replace(char old, char new) It replaces all occurrences of the specified
char value.
String replace(CharSequence old, It replaces all occurrences of the specified
CharSequence new) CharSequence.
static String equalsIgnoreCase(String It compares another string. It doesn't check
another) case.
String[] split(String regex) It returns a split string matching regex.
String[] split(String regex, int limit) It returns a split string matching regex and
limit.
String intern() It returns an interned string.
int indexOf(int ch) It returns the specified char value index.
int indexOf(int ch, int fromIndex) It returns the specified char value index
starting with given index.
Method Description
int indexOf(String substring) It returns the specified substring index.
int indexOf(String substring, It returns the specified substring index starting with
int fromIndex) given index.
String toLowerCase() It returns a string in lowercase.
String toLowerCase(Locale l) It returns a string in lowercase using specified locale.
String toUpperCase() It returns a string in uppercase.
String toUpperCase(Locale l) It returns a string in uppercase using specified locale.
String trim() It removes beginning and ending spaces of this string.
static String valueOf(int It converts given type into string. It is an overloaded
value) method.
int indexOf(String substring) It returns the specified substring index.
int indexOf(String substring, It returns the specified substring index starting with
int fromIndex) given index.
• java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.

• CharSequence interface is used to represent the sequence of


characters. String, StringBuffer and StringBuilder classes
implement it.

• It means, we can create strings in Java by using these three


classes.
2) Java StringBuffer Class
• used to create mutable (modifiable) String objects.

Table: Important Constructors of StringBuffer Class


Table: Important Methods of StringBuffer Class

Method Description
append(String s) It is used to append the specified string with this string.
The append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.
insert(int offset, String It is used to insert the specified string with this string at
s) the specified position. The insert() method is overloaded
like insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
replace(int startIndex, It is used to replace the string from specified startIndex
int endIndex, String str) and endIndex.
delete(int startIndex, int It is used to delete the string from specified startIndex and
endIndex) endIndex.
reverse() is used to reverse the string.
capacity() It is used to return the current capacity.
Table: Important Methods of StringBuffer Class (cont.)
Method Description
ensureCapacity(int It is used to ensure the capacity at least equal
minimumCapacity) to the given minimum.
charAt(int index) It is used to return the character at the
specified position.
length() It is used to return the length of the string i.e.
total number of characters.
substring(int beginIndex) It is used to return the substring from the
specified beginIndex.
substring(int beginIndex, int It is used to return the substring from the
endIndex) specified beginIndex and endIndex.
StringBuffer Class append() Method

class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");
//now original string is changed
System.out.println(sb); //prints Hello Java
}
}
StringBuffer insert() Method

class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");
//now original string is changed
System.out.println(sb); //prints HJavaello
}
}
StringBuffer replace() Method

class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");

sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo
}
}
StringBuffer delete() Method

class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb); //prints Hlo
}
}
StringBuffer reverse() Method

class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); //prints olleH
}
}
StringBuffer capacity() Method

class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity()); //default 16
sb.append("Hello");
System.out.println(sb.capacity()); //now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());
//now (16*2)+2=34 i.e (oldcapacity*2)+2
StringBuffer ensureCapacity() method
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
} }
3) Java StringBuilder Class
Table: Important Constructors of StringBuilder Class
Table: Important Methods of StringBuilder Class
Method Description
append(String s) It is used to append the specified string with this string. The
append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double)
etc.
insert(int offset, String It is used to insert the specified string with this string at the
s) specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
replace(int startIndex, It is used to replace the string from specified startIndex and
int endIndex, String str) endIndex.
delete(int startIndex, It is used to delete the string from specified startIndex and
int endIndex) endIndex.
reverse() It is used to reverse the string.

capacity() It is used to return the current capacity.


Table: Important Methods of StringBuilder Class (cont.)

Method Description
ensureCapacity(int It is used to ensure the capacity at least equal to the
minimumCapacity) given minimum.
charAt(int index) It is used to return the character at the specified
position.
length() It is used to return the length of the string i.e. total
number of characters.
substring(int beginIndex) It is used to return the substring from the specified
beginIndex.
substring(int beginIndex, int It is used to return the substring from the specified
endIndex) beginIndex and endIndex.
Difference between StringBuffer
and StringBuilder
No. StringBuffer StringBuilder

1) StringBuffer is synchronized i.e. StringBuilder is non-


thread safe. It means two synchronized i.e. not thread safe.
threads can't call the methods of It means two threads can call the
StringBuffer simultaneously. methods of StringBuilder
simultaneously.
2) StringBuffer is less efficient than StringBuilder is more
StringBuilder. efficient than StringBuffer.
3) StringBuffer was introduced in StringBuilder was introduced in
Java 1.0. Java 1.5.
public class ConcatTest{
public static void main(String[] args){
long startTime = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("Tpoint");
}
System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) +
"ms");
startTime = System.currentTimeMillis();
StringBuilder sb2 = new StringBuilder("Java");
for (int i=0; i<10000; i++){
sb2.append("Tpoint");
}
System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime)
+ "ms");

You might also like