Core Java Unit 2
Core Java Unit 2
BCA SEM - VI
Unit - 2
Prepared By:-BhaveshMehta
(bdmehta3300@gmail.com)
1
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
TOPIC – 1
Class, Object and Methods
Class:
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
Fields
Methods
Constructors
Blocks
Nested class and interface
Core properties include the data types and methods that may be used by the object. All class
objects should have the basic class properties.
Classes are categories, and objects are items within each category.
Class can contain any of the following variable types.
Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any method.
These variables are instantiated when the class is loaded. Instance variables can be
accessed from inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside any method,
with the static keyword.
The General Form of a Class:
classclsName
{
// instance variable declaration
type1 varName1 = value1;
type2 varName2 = value2;
:
typeNvarNameN = valueN;
// Methods
rType1 methodName1(mParams1)
{
// body of method
}
:
:
rTypeNmethodNameN(mParamsN)
{
// body of method
}
}
Example of a General Class
Class clsSample
{
// Variables
static intctr;
inti;
// Methods
int addition()
{
ctr++;
returni + j;
}
Int NumberOfInstances()
{
return ctr;
}
}
Nested class(Inner Classes):
“When we create class within a class is known as nested or inner class.”
Java supports inner classes, which are classes that can be defined in any scope.
This means that a class can be defined as a member of another class, within a block of
statements.
An inner class's name is not visible outside its scope, except in a fully qualified name.
The ability to nested classes allows any top-level class to provide a package-style for a logically
related group of secondary top-level classes.
Program :-
class Outer
{
Intouter_x=100;
void test()
{
Inner inner = new Inner();
inner.display();
}
//this is an inner class
class Inner
{
void display()
{
System.out.println("outer x ="+outer_x); // 100
}
}
}
Class InnerClassDemo
{
public static void main(String args[])
{
Outer outr = new Outer();
outr.test();
}
}
Object:
An Entity that has state and behavior is known as an object.
For example, chair, bike, marker, pen, table, car etc.
PREPARED BY: Bhavesh Mehta Page 3 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
It can be physical or logical.
The example of logical object is banking system.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used
to write, so writing is its behavior.
Object Definitions:
o An object is a real-world entity.
o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.
An object has three characteristics:
o State: represent data of an object. For example name of an object, colour etc.
o Behavior: represent the behavior (functionality) of an object such as deposit,
withdrawal etc..
o Identity: object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But, it is used internally by the JVM to identify each
object uniquely.
Declaring Objects:
You can create a class, you are creating a new data type. You can use this type of declare objects
of that type.
Obtaining of a class is a two step process.
First you must declare a variable of the class type. Second you must acquire an actual, physical
copy of the object and assign it to that variable.
You can do this using the new operator. The new operator dynamically allocates memory for
an object and returns a reference to it.
Syntax to declare an object :
Class_nameobject_variable = new class_name ();
Example :
class objdecl
{
class box
{
Int width, height, depth;
}
public static void main (String args[])
{
box b = new box();
}
}
By reference variable
o Initializing an object means storing data into the object. Let's see a simple example where
we are going to initialize the object through a reference variable.
o Example:
class Student{
int id;
PREPARED BY: Bhavesh Mehta Page 4 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
By method
o we are creating the two objects of Student class and initializing the value to these objects
by invoking the insertRecord method. Here, we are displaying the state (data) of the
objects by invoking the displayInformation() method.
o Example:
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();
}
}
By constructor
o We will learn in upcoming chapter.
Method:
In general, a method is a way to perform some task. Similarly, the method in Java is a collection
of instructions that performs a specific task.
It provides the reusability of code. We can also easily modify code using methods.
We write a method once and use it many times. We do not require to write code again and
again.
It also provides the easy modification and readability of code, just by adding or removing a
chunk of code.
The method is executed only when we call or invoke it.
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o 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.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by
its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a
verb followed by adjective or noun. In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
o In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods.
o It is also known as the standard library method or built-in method. We can directly
use these methods just by calling them in the program at any point.
o Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
o When we call any of the predefined methods in our program, a series of codes related
to the corresponding method runs in the background that is already stored in the
library.
o Each and every predefined method is defined inside a class.
o Such as print() method is defined in the java.io.PrintStream class.
o It prints the statement that we write inside the method. For example, print("Java"), it
prints Java on the console.
User-defined Method
o The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.
Call a Method
o To call a method in Java, write the method's name followed by two parentheses () and
a semicolon;
o In the following example, myMethod() is used to print a text (the action), when it is
called:
o Example:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
TOPIC – 2
Polymorphism: Method Overloading.
Introduction to polymorphism:
Polymorphism, which literally means “different forms”.
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.
The most common use of polymorphism in OOP occurs when a parent class reference is used to
refer to a child class object.
It is important to know that the only possible way to access an object is through a reference
variable. A reference variable can be of only one type. Once declared, the type of a reference
variable cannot be changed.
PREPARED BY: Bhavesh Mehta Page 7 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
The reference variable can be reassigned to other objects provided that it is not declared final.
The type of the reference variable would determine the methods that it can invoke on the
object.
A reference variable can refer to any object of its declared type or any subtype of its declared
type. A reference variable can be declared as a class or interface type.
We can perform polymorphism in java by method overloading and method overriding.
There are two types of polymorphism in Java: compile-time polymorphism (Static
polymorphism) and runtime polymorphism (Dynamic Method Dispetch).
o Compile Time Polymorphism (Static Polymorphism):
o This type of polymorphism is achieved by creating multiple methods with the same
name in the same class, but with each one having different numbers of parameters or
parameters of different data types.
o In the example below, notice that the three methods have the same name, but each
accepts a different number of parameters or different data types:
class Multiplier {
static void Multiply(int a, int b)
{
System.out.println("Integer Multiplication, Result = "+ a*b);
}
// Method 2
static void Multiply(double a, double b)
{
}
// Method 3
static void Multiply(double a, double b, double c)
{
System.out.println("Three parameters, double Multiplication, Result = "+ a*b*c);
}
}
public class Main {
public static void main(String[] args) {
// using the first method
Multiplier.Multiply(3,5);
// using the second method
Multiplier.Multiply(3.5,5.1);
// using the third method
Multiplier.Multiply(3.6,5.2, 6.3);
}
}
Inheritance Polymorphism
Inheritance is one in which a new class Whereas polymorphism is what can be
(derived class) is formed that inherits characterized in different ways.
1 1
the characteristics from the current
class(base class).
Basically, it is used for lessons. Whereas functions or techniques are
2 2
simply implemented.
The principle of reusability is Polymorphism enables the object to
supported by inheritance and determine which function type is to be
3 3
decreases code length in object- enforced at both compile-time
oriented programming. (overloading) and run-time (overriding).
Inheritance may be an inheritance of Whereas-time polymorphism (overload)
4 pure, mixed, mixed, hierarchical and 4 as well as run-time polymorphism
multilevel. (overriding) can be compiled.
5 In pattern building, it is used. 5 Since it is also used in creating patterns.
Method Overloading
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int, int) for two parameters, and b(int, int, int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behavior of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
TOPIC – 3
Constructor: Concept of Constructor, Types of Constructor, Constructor
Overloading.
Introduction to Constructor:
“A constructor is used to initialize the objects of its class.”
When you create an object, you typically want to initialize its member variables.
It is special because its name is the same as the class name.
The constructor is invoked automatically whenever an object of its associated class is
created.
It is called constructor because it construct the values of data member of the class.
The constructor is a special method you can implement in all your classes; it allows you
to initialize variables and perform any other operations when an object is created from
the class.
Characteristics of Constructor:
The constructor has always the same name as the class
If we don’t define any constructor than compiler automatically define it.
There is no return type define in the constructor.
There is no return statement require in the body of the constructor.
We can use “this” to call another constructor in the same class.
We can use “super” to call a constructor in a parent class.
Syntax
Following is the syntax of a constructor:
class ClassName
}
}
Types of Constructor:
There are three types of constructors (1) Default (2) Parameterized (3) Copy
o Default constructor:
o A constructor is called "Default Constructor" when it doesn't have any parameter.
o If there is no constructor in a class, compiler automatically creates a default
constructor.
o This type of constructor is not visible in the program; it automatically creates without
definition and declaration in the class.
Syntax of default constructor:
<class_name>(){}
Example:
/Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
o Parameterized constructor:
o It contains parameters (or arguments) in the constructor definition and declaration.
More than one argument can also be passed through parameterized constructor in
Java.
Syntax of default constructor:
<class_name>(<datatype><var1>,…….,<datatype><varN>){}
Example:
class Rectangle
{
double length;
double breadth;
Rectangle()
{
length = 10;
breadth = 20;
}
Rectangle(double l, double b)
{
length = l;
breadth = b;
}
PREPARED BY: Bhavesh Mehta Page 12 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
double calculateArea()
{return length*breadth;}
}
class Rectangle_Main {
public static void main(String[] args) {
double area;
Rectangle myrec = new Rectangle(41,56);
area = myrec.calculateArea();
System.out.println("The area of Rectangle: " +area);
}
}
o Copy constructor:
o A copy constructor is a special type constructor which creates an object using another
object of the same class. In return, it gives a copy of an already created object that is
copied.
Syntax of default constructor:
<class_name>(<class name><Obj_var1>,…….,<class name><Obj_varN>){}
Example:
class Rectangle
{
private double length;
private double breadth;
//copy constructor
Rectangle(Rectangle rect)
{
System.out.println("Copy Constructor Invoked!!");
length = rect.length;
breadth = rect.breadth;
}
//method to return area
double calculateArea()
{
return length*breadth;
}
}
class Rectangle_Main{
Constructor overloading:
“When we declare more than one constructor in a class is known as constructor
overloading or multiple constructor.”
Ex :-
// Multiple Constructor or constructor overloading
class Box
{
double width;
double height;
double depth;
// construct clone of an object
Box(Box ob)
{
// pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// parameterized constructor
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// default constructor
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
PREPARED BY: Bhavesh Mehta Page 14 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
}
// parameterized constructor to assign same value to all the variables
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class ConstructorOver
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15); // 3 parameter constructor call
Box mybox2 = new Box(); //default constructor call
Box mycube = new Box(7); //1 parameterized constructor call
Box myclone = new Box(mybox1);// object as parameter constructor call
doublevol;
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
Volume of myclone is 3000.0
TOPIC – 4
Garbage Collection, Finalize () Method
Garbage Collection:
Garbage Collection in Java is a process by which the programs perform memory management
automatically.
The Garbage Collector(GC) finds the unused objects and deletes them to reclaim the memory.
In Java, dynamic memory allocation of objects is achieved using the new operator that uses
some memory and the memory remains allocated until there are references for the use of the
object.
When there are no references to an object, it is assumed to be no longer needed, and the
memory, occupied by the object can be reclaimed.
There is no explicit need to destroy an object as Java handles the de-allocation automatically.
The technique that accomplishes this is known as Garbage Collection. Programs that do not de-
allocate memory can eventually crash when there is no memory left in the system to allocate.
These programs are said to have memory leaks.
Garbage collection in Java happens automatically during the lifetime of the program,
eliminating the need to de-allocate memory and thereby avoiding memory leaks.
In C language, it is the programmer’s responsibility to de-allocate memory allocated
dynamically using free() function. This is where Java memory management leads.
Note: All objects are created in Heap Section of memory.
Uncomment line # 23 & 24. Compile, Save & Run the code
As show in diagram below, s2 becomes null, but s3 is still pointing to the object and is not
eligible for java garbage collection.
finalize( ) method:
The mechanism to destroy reference file or external resources which are used in your program,
is known as finalize( ) method.
Sometimes an object will need to perform some action when it is destroyed.
For example, if an object is holding some non-Java resource such as a file handle or window
character font, then you might want to make sure these resources are freed before an object is
destroyed.
To handle such situations, Java provides a mechanism called finalization.
By using finalization, you can define specific actions that will occur when an object is just about
to be reclaimed by the garbage collector.
To add a finalizer to a class, you simply define the finalize ( ) method.
Inside the finalize( ) method you will specify those actions that must be performed before an
object is destroyed(before gc called).
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
It is important to understand that finalize ( ) is only called just prior to garbage collection.
In the above program, when the String object a holds value Hello World! it has a reference to an
object of the String class. But, when it holds a null value it does not have any reference. Hence,
it is eligible for garbage collection. The garbage collector calls finalize() method to perform
clean-up before destroying the object.
TOPIC – 5
The ‘this’ keyword.
Introduction:
The this keyword refers to the current object in a method or constructor.
The most common use of the this keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed by a
method or constructor parameter).
If you omit the keyword in the example above, the output would be "0" instead of "5".
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
PREPARED BY: Bhavesh Mehta Page 21 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
s1.display();
s2.display();
}}
Output:
111 ankit 5000.0
112 sumit 6000.0
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10
1.
o this can be used to return the current class instance from the method.
We can return this keyword as an statement from the method. In such case, return type of
the method must be the class type (non-primitive). Let's see the example:
Syntax of this that can be returned as a statement
return_type method_name(){
return this;
}
Example
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
TOPIC – 6
‘static’ and ‘final’ keyword.
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:
o Variable (also known as a class variable)
o Method (also known as a class method)
o Block
o Nested class
Java static variable
o If you declare any variable as static, it is known as a 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.
Advantages of static variable
o It makes your program memory efficient (i.e., it saves memory).
Understanding the problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
o Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and
name, so instance data member is good in such case. Here, "college" refers to the
common property of all objects. If we make it static, this field will get the memory only
once.
Example of static variable
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
nested class
o 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.
It can access static data members of the outer class, including private.
The static nested class cannot access non-static (instance) data members or
o Java static nested class example with instance method
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
PREPARED BY: Bhavesh Mehta Page 26 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Output:
data is 30
o In this example, you need to create the instance of static nested class because it has
instance method msg(). But you don't need to create the object of the Outer class
because the nested class is static and static properties, methods, or classes can be
accessed without an object.
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
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. 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.
We will have detailed learning of these. Let's first learn the basics of final keyword.
Java final variable
o If you make any variable as final, you cannot change the value of final variable(It will be
constant).
o Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable,
but It can't be changed because final variable once assigned a value can never be
changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output: Compile Time Error
Java final method
o If you make any method as final, you cannot override it.
o Example of final method
class Bike{
final void run(){System.out.println("running");}
}
TOPIC – 7
Access Control: Public, Private, Protected and Default.
class B extends A{
PREPARED BY: Bhavesh Mehta Page 29 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output: Hello
Public
o The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
o Example of public access modifier
//save by A.java
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output: Hello