CH 1 - Part 2
CH 1 - Part 2
CH 1 - Part 2
Ch1
1_2
Classes , Objects,
Encapsulation,Inheritance,polymorphism
Class
To define a class class keyword is used. Following is the general
form of a class definition.
class className
{
dataType var1;
dataType var2;
…………….
dataType varn;
className(type param1, type param2,..) //Constructor
{ //statements..
}
returnType method1(type param1,type param2,..)
{
//statements..
}
returnType methodN(type param1,type param2,..)
{
//statements…..
}
Here, className can be any valid identifier. Var1,var2,varN are
instance variables class className.
Instance variables are also known as member variables or data.
Method1, methodN are methods that return value of type
returnType.
The formal parameters are specified with the data type in
parenthesis. These methods are also known as member functions.
1
The constructor is a method that has same name as class name.
Note that in general form we have not specified the main method
because the main method is not compulsory for all classes.
Only one class of your program can contain main method which is
the starting point of program execution.
Example
class bank
{
double p,r,n;
}
class prg1 {
public static void main(String args[]) {
bank b1=new bank();
b1.p=5000;
b1.r=12;
b1.n=5;
double si=b1.p*b1.r*b1.n/100;
System.out.println(“simple Interest of b1 :”+si);
}
}
Creating objects
Here, the class bank has three instance variable. So after creating
it object can access these variables.
2
new keyword
Here, the new keyword is used to allocate memory equal to the
size of instance variables of class bank. Before using new keyword
the object can not be used.
So you can say that the object gets physical existence after the
memory allocation by new keyword.
returnType methodName(parameter-list) {
//statement
//optional return statement
}
Here, returnType is the type of value or express the method will
return. If the method doesn‟t return a value, the returnType should
be void. Parameter list is the list of parameter that the method takes
separated by commas.
class bank
{ double p,r,n;
void simpleinterest()
{ double si;
si=p*r*n/100;
System.out.println(“simple Interest of b1 :”+si);
}
3
}
class prg1 {
public static void main(String args[]) {
bank b1=new bank();
b1.p=5000;
b1.r=12;
b1.n=5;
b1. simpleinterest(); //calling method on object b1
}
}
Encapsulation:-
For any computer program, two core elements are data and function.
Structured/Procedural programming views these two core elements as two
separate entities; whereas object-oriented programming views them as single
entity.
In procedural programming, data can be altered by any component of the
program. It is not protected from modification.
In object-oriented programming, this problem can be solved using
encapsulation.
Here, data and the methods that manipulate data are guarded against
modification of program is called ENCAPSULATION.
This is possible by wrapping data and methods into a single unit known as
class and declaring them as private.
Private members of the class are not available directly to outside world. If
necessary, the data is made available via public methods.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Inheritance:-
Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another. With the use of inheritance the
information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as
super class (base class, parent class).
4
Extends is the keyword used to inherit the properties of a class. Following is
the syntax of extends keyword.
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Constructors
The constructor is a special method which has the same name
as its class. It initializes the object of its class automatically at
the time of creation.
One important point about constructor is that they have no
return type. Not even void.
This is because they actually return the object of its class.
When we create an object, we call the constructor after new
keyword. So the statements written in the constructor are
executed at that time.
There are three types of Constructors
1) Default Constructor
2) Parameterize Constructor
3) Copy Constructor
class bank {
double p,r,n;
bank()
{
System.out.println(“executing constructor..”);
p=10000;
r=12;
n=5;
}
double simpleinterest()
{
return (p*r*n/100);
}
}
class prg1
{
public static void main(String args[])
{
bank b1=new bank(); //calling constructor
double si=b1.simpleinterest(); //calling method on object
System.out.println(“simple interest is”+si);
}
}
5
Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to
another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They
are:
o By constructor
o By assigning the values of one object into another
class student
{
int d;
String name;
student(int i,String n)
{
id=i;
name=n;
}
student(student s)
{
id=s.id;
name=s.name;
}
void display()
{
System.out.println(id+ " "+name);
}
public static void main(String arg[])
{
student s1 = new student(30,"RPBC");
student s2 = new student(s1);
s1.display();
s2.display();
}
}
6
class Point
{
int x,y;
void init(int x,int y)
{
this.x=x;
this.y=y;
}
void display()
{
System.out.println("X="+x);
System.out.println("Y="+y);
}
}
class This_Keyword
{
public static void main(String arg[])
{
Point p = new Point()
p.init(4,3);
p.display();
}
}
Method overloading
As we know that polymorphism is an important feature of oop.
Method overloading is a way by which java achieves
polymorphism.
In a class you can define more than one method.
When in a class there is more than one method with same
name but different number & types of parameters, the method
is said to be overloaded & this process is known as method
overloading.
We can see in below example.
class area
{ void area()
{
System.out.println(“area is zero”);
}
void area(double r)
{
double a=3.14*r*r;
System.out.println(“area of circle is”+a);
}
void area(double l,double w)
{
double a= l *w;
7
System.out.println(“area of rectangle is:”+a);
}
}
class prg1
{
public static void main(String args[])
{
area a=new area();
a.area(); //area() with no parameters
a.area(10.0); //area() with one parameter
a.area(15,10); //area() with two parameter
} }
Constructor overloading
We can also overload constructor in java. When we create more than
one constructor with different parameters, it is called constructor
overloading.
Sometimes it is needed to create objects with less or no parameter.
We can see in example.
class bank {
double p,r,n;
bank()
{
p=0; r=0;n=0;
}
bank(double p)
{
this.p=p;
this.r=12;
this.n=1;
}
double simpleinterest()
{
return (p*r*n/100);
}
}
class prg1
{
public static void main(String args[])
{
bank b1=new bank();
bank b2=new bank(10000);
double si=b1.simpleinterest();
8
finalize() Method
In C++ we have a special function called destructor to free the memory
utilized by the variable and methods.
We also know that java does not support destructor.
So that java has given a special method called finalize() which will work
same as the destructor.
This method comes from java.lang.Object.finalize().
This method called garbage collector clearing the memory.
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.
To do so, we were using free() function in C language and delete() in C++.
But, in java it is performed automatically. So, java provides better memory
management.
The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This
method is defined in Object class as: protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are
created by new keyword. So if you have created any object without new, you
can use finalize method to perform cleanup processing (destroying remaining
objects).
gc() method The gc() method is used to invoke the garbage collector to
perform cleanup processing. The gc() is found in System and Runtime
classes.
Note: Garbage collection is performed by a daemon thread called Garbage
Collector (GC). This thread calls the finalize() method before object is
garbage collected.
class TestGarbage1{
public void finalize()
{
System.out.println("object is garbage collected");
}
void display()
{
System.out.println();
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
s1.display();
}
}
9
Static and non-static Member
static member:-
Static member is also known as class variable or class method.
What is the reason static member known as class variable & method??
Answer is that, static member shared common value of the all object.
Static member invokes in memory only one time when class is created.
Static member of class are stored in class.
How to declare static member:-
static int a;
static void display()
static member accessing by name of the class. Her do not use the object of
the class for the static member.
non-static member:-
non static member classified by in two category.
Instance variable and local variable.
Instance variable:-
o These types of variable are always define in class but outside the any
method.
o These variables access by the object of the class.
o These variables are allocated memory from heap where object is
created.
Local variable:-
o Local variable are always define in method or block of any class.
o Local variable are not initialized by the default value.
o They are created when the method or bock is started & destroyed when
the method or block has completed.
class Counter
{
int count=0;
static int b=0;
Counter()
{
b++;
count++;
System.out.println("B="+b);
System.out.println("Count="+count);
}
10
Difference B/W non-static and static variable :-
varargs
In JDK 5, Java has included a feature that simplifies the creation of methods
that need to take a variable number of arguments. This feature is called
varargs and it is short-form for variable-length arguments.
A method that takes a variable number of arguments is a varargs method.
Prior to JDK 5, variable-length arguments could be handled two ways.
One using overloaded method(one for each) and another put the arguments
into an array, and then pass this array to the method. Both of them are
potentially error-prone and require more code.
The varargs feature offers a simpler, better option.
Syntax of varargs:-
A variable-length argument is specified by three periods(…). For Example,
11
// Driver code
public static void main(String args[])
{
// Calling the varargs method with different number
// of parameters
fun(100); // one parameter
fun(1, 2, 3, 4); // four parameters
fun(); // no parameter
}
}
12