0% found this document useful (0 votes)
32 views37 pages

CH - 02

The document discusses key concepts related to classes and objects in Java, including: 1. A class defines a new data type and acts as a blueprint for creating objects with state and behavior. 2. An object is an instance of a class that has unique identity, state, and behavior. 3. Constructors are special methods used to initialize objects, and can be default, parameterized, or overloaded.

Uploaded by

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

CH - 02

The document discusses key concepts related to classes and objects in Java, including: 1. A class defines a new data type and acts as a blueprint for creating objects with state and behavior. 2. An object is an instance of a class that has unique identity, state, and behavior. 3. Constructors are special methods used to initialize objects, and can be default, parameterized, or overloaded.

Uploaded by

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

CH – 02

CLASSES AND OBJECTS

05/08/2017 Nikita Education (NET) 1


Class
• In Java everything is encapsulated under classes.
• Class is the core of Java language.
• Class can be defined as a template/ blueprint that describe the behaviors /states
of a particular entity.
• A class defines new data type.
• Once defined this new type can be used to create object of that type.
• A class is declared using class keyword.

Syntax: public class Dog{


int ageC;
class <class_name>{ String color;
void hungry(){ }
Data members; void sleeping(){ }
Member method; public static void main(String args[]){ }
Main method; }
} 05/08/2017 Nikita Education (NET) 2
Object
• An entity that has state and behavior is known as an object e.g.
chair, bike, marker, pen, table, car etc.
• Object is an instance of a class.
• Creating an Object:
– Syntax: ClassName objectRef = new ClassName();
– Example: Student studRef = new Student();

• Accessing members using objects


– Instance variables:
• Syntax: objectRef.varibaleName;
• Example: studRef.rollNumber;
– Instance methods i.e. non-static methods:
• Syntax: objectRef.methodName();
• Example: studRef.registerStudent();
05/08/2017 Nikita Education (NET) 3
Array of Objects
class DemoArrayOfObjects
{
int rollno;
String sname;
public DemoArrayOfObjects()
{
rollno=145108;
sname=“Nikita”;
}
public static void main(String [] args)
{
DemoArrayOfObjects array[]=new DemoArrayOfObjects[5];
for(int i=0; i<5; i++)
{
array[i] = new DemoArrayOfObjects();
}
for(int i=0; i<5; i++)
{
System.out.println(array[i].toString());
}
}
05/08/2017 Nikita Education (NET) 4
}
Constructors
• A constructor is a special method that is used to initialize an object members.
• Every class has a constructor.
• If we don't explicitly declare a constructor for any java class the compiler builds a default
constructor for that class.
• A constructor does not have any return type.
• A constructor has same name as the class in which it resides.
• Constructor in Java cannot be abstract, static, final or synchronized. These modifiers are
not allowed for constructor.
• Java constructor is invoked automatically at the time of object creation.
• 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

05/08/2017 Nikita Education (NET) 5


Default Constructor
class Student{
int id;
String name;
public Student() //default constructor
{
id=145108;
name=“Manoj”;
}
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.display();
s2.display();
}
}
05/08/2017 Nikita Education (NET) 6
Parameterized Constructor
class Student{
int id;
String name;
public Student(int roll,String studname) //parameterized constructor
{
id=roll;
name=studname;
}
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student s1=new Student(145105, “Nikita”);
Student s2=new Student(145108, “Nachiket”);
s1.display();
s2.display();
}
}
05/08/2017 Nikita Education (NET) 7
Constructor Overloading
class Student{
int id; public Student(int roll, String s1)
String name; {
public Student() id=roll;
{ name=s1;
id=145108; }
name=“Manoj”; void display(){
System.out.println(id+" "+name);
}
}
public Student(int roll)
public static void main(String args[]){ Student o1=new
{ Student();
id=roll; Student o2=new Student(145123);
name=“Ajay”; Student o3=new Student(“Rutuja”);
} Student o4=new Student(145150,”Neha”);
public Student(String s1) o1.display();
{ o2.display();
id=145114; o3.display();
name=s1; o4.display();
} }
05/08/2017 Nikita Education (NET) 8
}
this
• this keyword is used to refer to current object.
• this is always a reference to the object on which method was invoked.
• this can be used to invoke current class constructor.
• this can be passed as an argument to another method.

class Student{
int id; public static void main(String args[]){
String name; Student s1 = new Student(111,"Karan"); Student s2 =
Student(int id, String name){ new Student(222,"Aryan");
this.id = id; s1.display();
this.name = name; s2.display();
}
} }
void display(){
System.out.println(id+" "+name);
}

05/08/2017 Nikita Education (NET) 9


Garbage Collection
• In java, garbage means unreferenced objects.
• Garbage Collection is process of reclaiming the runtime unused memory
automatically.
• In other words, it is a way to destroy the unused objects.
• It makes java memory efficient
• It is automatically done by the garbage collector(a part of JVM)
• How can an object be unreferenced?
– By nulling the reference
– By assigning a reference to another object
– By anonymous object etc.

05/08/2017 Nikita Education (NET) 10


finalize() method
• In java, finalize method is used to perform cleaning work just before destroying an object.
• Cleaning work can be closing file handler, closing database connections, closing network
sockets, stopping web services etc.
• In java, finalize() method is automatically called by garbage collector just before
destroying the object.
• It's the last chance for any object to perform cleanup utility.
• The finalize() method is invoked each time before the object is garbage collected.
• Example:
public class TestGarbage1{

protected void finalize(){


dbconn.close();
}
}

05/08/2017 Nikita Education (NET) 11


Nested classes
• When class is defined inside another class then such class is called as nested class.

05/08/2017 Nikita Education (NET) 12


static variable
• If variable is declared using static keyword then it is called as static variable.
• Static variable is commonly shared by all the objects.
• It gets memory only once in the class area when it is created.
• Static variable is memory efficient.
• Syntax: static datatype varname;
• Example:
class DemoStaticVariable{
static int rollNo=145105;
static float marks=80.23f;
static String sname=“gpn”;
static void display()
{
System.out.println(rollNo + “,” + marks + “,” + sname);
}
}
05/08/2017 Nikita Education (NET) 13
static method
• If method is declared using static keyword then it is called as static method.
• Static method belongs to class rather than objects.
• It can be invoked without creating object of class.
• In other class it can be invoked by using class name.
• Syntax: static returntype methodname();
• Syntax to access in other class: classname.methodName();
• Example:
class DemoStaticVariable{
static int rollNo=145105;
static void display()
{
System.out.println(“Example of static method”);
}
}

05/08/2017 Nikita Education (NET) 14


static block
• Is used to initialize the static data member.
• It is executed before main method at the time of classloading.
• Example:
class DemoStaticVariable{
static int rollNo;
static float marks;
static String s1,s2,s3;
static{
rollno=05;
marks=75.23f;
s1=“KKW”;
s2=“GPN”;
s3=“MVP”;
}
}
05/08/2017 Nikita Education (NET) 15
extends keyword
• extends keyword is used to inherit the properties of one class into another class.

• Syntax: class Super{


}
class Sub extends Super{
}

• Example: class Vehicle{


......
}
class Car extends Vehicle{
....... //extends the property of vehicle class.
}

05/08/2017 Nikita Education (NET) 16


super keyword
• super keyword is used to access members of immediate super class of sub
class.
• It is used to differentiate members of super class from its sub class if they
have same member names.
• It is used to invoke constructor of super class from sub class.
• super() must be the first statement in sub class constructor.
• Syntax:
– To access variables: super.variablename;
– To access methods: super.methodname();
– To invoke constructor: super(); or super(parameters);

05/08/2017 Nikita Education (NET) 17


super keyword example
class Parent{
String name;
public void details(){
System.out.println(name);
}
}
public class Child extends Parent {
String name;
public void details(){
super.name=“Parent”;
super.details(); //calling Parent class details() method
name = "Child";
System.out.println(name);
}
public static void main(String[] args){
Child cobj = new Child();
cobj.details();
}
05/08/2017 Nikita Education (NET) 18
}
Method Overriding
class Bank{ class Test2{
int getRateOfInterest(){return 0;} public static void main(String args[]){
} SBI s=new SBI();
class SBI extends Bank{ ICICI i=new ICICI();
AXIS a=new AXIS();
int getRateOfInterest(){return 8;}
System.out.println(
} "SBI Rate of Int
class ICICI extends Bank{ erest: "+s.getRateOfInterest());
int getRateOfInterest(){return 7;} System.out.println(
} "ICICI Rate of In
terest: "+i.getRateOfInterest());
class AXIS extends Bank{
System.out.println(
int getRateOfInterest(){return 9;} "AXIS Rate of In
} terest: "+a.getRateOfInterest());
}
}

05/08/2017 Nikita Education (NET) 19


Dynamic method dispatch
class Animal{
void eat(){ public class Test{
System.out.println("eating"); public static void main(String args[]){
} Animal a;
}
a=new Animal();
class Dog extends Animal{
a.eat();
void eat(){ System.out.println("eating fruits");
} a=new Dog();
} a.eat();
class BabyDog extends Dog{
a=new BabyDog();
void eat(){
a.eat();
System.out.println("drinking milk");
} }
} }

05/08/2017 Nikita Education (NET) 20


final keyword

• The final keyword in java is used to restrict the user.


• The java final keyword can be used in many context.
• Final can be: variable, method, or class
• Value of final variable is constant
• Final method can not be overridden in sub classes
• Final class can not be inherited by any class

05/08/2017 Nikita Education (NET) 21


final variable
public class Test{
// The following are examples of declaring constants:
final int value = 10;
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";

public void changeValue(){


//following will give an error
value = 12;
BOXWIDTH = 8;
}
}

05/08/2017 Nikita Education (NET) 22


final method
class Bike{
final void run(){
System.out.println("running");
}
}
class Honda extends Bike{
void run(){ //can’t override
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
Output: Compile Time Error
}
} 05/08/2017 Nikita Education (NET) 23
final class
final class Bike
{
}
class Honda1 extends Bike{ //can’t extends
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda1 honda= new Honda();
honda.run();
}
}
Output: Compile Time Error

05/08/2017 Nikita Education (NET) 24


Abstract classes & methods
• A method that is declared as an abstract and does not have an
implementation is known as abstract method
• A class contains abstract methods and declared as an abstract is known as
abstract class
• Abstract methods of abstract class must be implemented by its child class or
it can be abstract
• Example:
– abstract class AbstractDemo
– {
– abstract void add();
– }
• Abstract class can not be instantiated
05/08/2017 Nikita Education (NET) 25
abstract class
abstract class Shape{
abstract void draw();
}
class Rect extends Shape{
void draw(){
System.out.println("drawing rectangle");
}
} class TestAbstraction1{
class Circle extends Shape{ public static void main(String args[]){
void draw(){ Shape s=new Circle();
System.out.println("drawing circle"); s.draw();
}
Shape s=new Rect();
}
s.draw();
}
}
05/08/2017 Nikita Education (NET) 26
Abstract class vs. Concrete class
• Abstract class:
– It is must to declare a class with an abstract access modifier .
– May or may not contain abstract methods.
– It is not possible to instantiate a abstract class .
– Variables are not final by default. We can able to reassign values.
– The abstract methods should implement in the derived classes. If not , the derived class also become
an abstract.
– Interface implementation is possible.
• Concrete class:
– Should not declare a concrete class with an abstract access modifier.
– Should not contain abstract methods.
– Instantiation is possible for a concrete class.
– Variables are not final by default.
– There is no abstract methods in any level to implement.
– Interface implementation is possible.
05/08/2017 Nikita Education (NET) 27
Visibility controls / Access specifiers
• Default : Default has scope only inside the same package
• Public : Public scope is visible everywhere
• Protected : Protected has scope within the package and all sub classes
• Private : Private has scope only within the classes

05/08/2017 Nikita Education (NET) 28


String class
• In java, string is not primitive data type
• It is an object of String class which represents sequence of characters
• Object of string is immutable means it can not be changed once it is created, every
time new object is created when value of string is changed
• Example:
– String s1=“Nikita Education”; or
– String s2=new String(“Nikita Education”);
• String class provides various methods to support different string related
operations for example concat, reverse, length, lower, upper, substring etc.

05/08/2017 Nikita Education (NET) 29


String class methods
Method Description
char charAt(int index) returns char value for the particular index
int length() returns string length
String substring(int beginIndex, int endIndex) returns substring for given begin index and
end index
String concat(String str) concatinates specified string
String trim() returns trimmed string omitting leading and
trailing spaces
int indexOf(int ch) returns specified char value index
String toLowerCase() returns string in lowercase.
String toUpperCase() returns string in uppercase.

05/08/2017 Nikita Education (NET) 30


StringBuffer class
• StringBuffer class is used to create a mutable string object means it can
change or modify exsting string values.
• It represents growable and writable character sequence.
• Constructors:
– StringBuffer() creates an empty string buffer with the initial capacity of
16.
– StringBuffer(String str) creates a string buffer with the specified string.
– StringBuffer(int capacity) creates an empty string buffer with the
specified capacity as length.

05/08/2017 Nikita Education (NET) 31


StringBuffer class methods
• public synchronized StringBuffer append(String s)
– 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.
• public synchronized StringBuffer insert(int offset, String s)
– is used to insert the specified string with this string at 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.
• public synchronized StringBuffer delete(int startIndex, int endIndex)
– is used to delete the string from specified startIndex and endIndex.
• public synchronized StringBuffer reverse()
– is used to reverse the string.
• public int capacity()
– is used to return the current capacity.

05/08/2017 Nikita Education (NET) 32


String vs. StringBuffer
String StringBuffer
String class is immutable. StringBuffer class is mutable.
String is slow and consumes more StringBuffer is fast and consumes less
memory when you concat too many memory when you cancat strings.
strings because every time it creates new
instance.
String class overrides the equals() StringBuffer class doesn't override the
method of Object class. So you can equals() method of Object class.
compare the contents of two strings by
equals() method.

05/08/2017 Nikita Education (NET) 33


Vector class
import java.util.*;
public class VectorDemo {
public static void main(String args[]) {
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " + v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
05/08/2017 Nikita Education (NET) 34
System.out.println("Current capacity: " +v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " +(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
05/08/2017 Nikita Education (NET) 35
}
Vector vs. ArrayList
ArrayList Vector
ArrayList is not synchronized. Vector is synchronized.
ArrayList increments 50% of current array size Vector increments 100% means doubles the
if number of element exceeds from its capacity. array size if total number of element exceeds
than its capacity.

ArrayList is not a legacy class, it is introduced Vector is a legacy class.


in JDK 1.2.
ArrayList is fast because it is non-synchronized. Vector is slow because it is synchronized.

ArrayList uses Iterator interface to traverse the Vector uses Enumeration interface to traverse
elements. the elements. But it can use Iterator also.

05/08/2017 Nikita Education (NET) 36


Wrapper classes
• Used to convert
– Values of primitive data types into object types or
– Object types into primitive types
• Following are the wrapper classes
Primitive Wrapper
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
05/08/2017 Nikita Education (NET) 37

You might also like