You are on page 1of 122

Module 2

• Class Fundamentals
• Declaring objects and assigning object reference variables
array of objects
• constructors .
• Methods
• overloading methods
• constructors
• this keyword
• static block
• nested class
• inner class
• garbage collection.
• finalize()- Inheritance – types - use of super - Polymorphism – abstract class –
interfaces – packages and sub packages.
Class Fundamentals
• A class can be defined as a template that describes
the functionalities /attributes that the instance of
this class could support
• Classes tell the compiler how to build a certain
object during runtime.
• Object – The object which is an instance of a class
have both functionalities and attributes.
– Example: A car has attributes like colour, number of
wheel, model ,price and functionalities like forward,
reverse, switch on indicators, cleaning windshield etc.,
Basic Structure of a Class
class <name> {
fields ;
methods;
}
Classes and Objects (Examples)

Class: Dog Class: Mobile Class: Car


Attributes: Attributes: Attributes:
Colour Number No_of_Seat
Name Service Car_Make
Breed Provider Fuel_type
Functionalities Operating Functionalities
Barking System Forward
Eating Functionalities Reverse
Wagging the Make_Call Windshield
tail Hear_Music Clean
Check_Mail

5
Object and Object Reference
• Object is an instance of a class and class is a
template; here Car and Dog are classes shown
below

Germ Bull Labra Maru Hyun


Ford
an Dog dor thi dai

6
Creating Objects
Rectangle rect1;//Declare the object
Rect1=new Rectangle();//instantiate the object

Rectangle Rect1=new Rectangle();//Both


statement combined.
We can create more objects
Dog German = New
Dog();
Dog German = new Dog(); Dog Bulldog = New
Dog();
Dog Labrador = New
Dog();
Instance
name
Class
name
Here , German is a memory reference to a Dog class
object stored in memory Colour
German Name
Breed

8
Arrays of Objects

• An array is a collection of homogeneous


typed variables that are referred to by a
common name
• To create multiple objects, array of objects
are created
• Arrays can hold only memory reference to
the objects; not the actual object.

9
Syntax for Array of Object Creation
Classname identifier[] = new Classname [size];
where size is the number of array objects
required
Output
Output
Constructors
• In Java, 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.
Rules for creating constructor :
• Constructor name must be the same as its
class name
• A Constructor must have no explicit return
type
Constructor Types :
• Default constructor
• Parameterized constructor.
Default Constructor
• A constructor is called "Default Constructor"
when it doesn’t have any parameter
Purpose of Default Constructor
It used to provide the default values to the
object like 0, null.
Another Example
Parameterized Constructor
• A constructor which has a specific number of
parameters.
• It is used to provide different values.
Method Overloading
• Multiple methods in a class, can have the
same name with different parameters.
• To perform only one operation, having same
name of the methods increases the readability
of the program
Methods in Java
• Methods are functionalities defined to operate on class
data members
• In the above example of student class show() is a
method which displays the data member of student
class
• A method can be static or non static
• Static method can be invoked without an object of that
class.
• Non static method should be invoked by an object of
that class.
Static and non static
Constructor Overloading
• In Java, a constructor is just like a method but
without return type.
• It can also be overloaded like Java methods.
• It is a technique of having more than one
constructor with different parameter lists.
• They are arranged in a way that each constructor
performs a different task.
• They are differentiated by the compiler by the
number of parameters in the list and their types.
Example2
Java Constructor vs Java Method
• A constructor must not have a return type.
• A method must have a return type.
• The constructor is invoked implicitly
• The method is invoked explicitly.
• The constructor name must be same as the
class name.
• The method name may or may not
be same as the class name
this Keyword
• There can be a lot of usage of java this keyword. In java,
this is a reference variable that refers to the current
object.
• this can be used to refer current class instance variable.
• this can be used to invoke current class method
(implicitly)
• this() can be used to invoke current class constructor.
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
Example-1. (Problem without this)
Example-2. (Solution)
Example-3.(Not required this)
Java Modifiers
• Modifiers are keywords used to change their meanings.
Java has a wide variety of modifiers, including the
following:
• Access Modifiers : to set access levels for classes,
variables, methods and constructors. The four access
levels are :
• default : Visible to the package
• private : Visible to the class only
• public : Visible to the world.
• protected : Visible to the package and all subclasses.
Non Access Modifiers
• static : used for creating class methods and
variables.
• final : used for finalizing the implementations
of classes, methods, variables.
• abstract : used for creating abstract classes
and methods.
• synchronized and volatile modifiers, which
are used for threads
private Access Modifier
private Access Modifier
default Access Modifier

The scope of class A and its method msg() is


default so it cannot be accessed from
outside the package.
protected Access Modifier
• Created the two packages pack and mypack.
The A class of pack package is public, so can
be accessed from outside the package. But
msg() of this package is declared as protected,
so it can be accessed from outside the class
only through inheritance
public Access Modifier
• It is accessible everywhere. It has the widest
scope among all other modifiers.
public
Nested Classes

• In Java, just like methods, variables of a class


too can have another class as its member.
Writing a class within another is allowed in
Java. The class written within is called
the nested class, and the class that holds the
inner class is called the outer class.
• Which increase the use of Encapsulation and
create more readability and maintainable of
the code.
• A nested class has access to the private
members.
• A nested class can be declared private, public,
protected.
• Advantage of java inner classes
– To develop more readable and maintainable
code.
– Code Optimization: It requires less code to write.
– It can access all the members (data members and
methods) of outer class including private.
• Syntax
Following is the syntax to write a nested class.
Here, the class Outer_Demo is the outer class
and the class Inner_Demo is the nested class.
Nested classes are divided into two categories:
 static nested class : Nested classes that are
declared static are called static nested classes.
 inner class : An inner class is a non-static
nested class.
Inner Classes (Non-static Nested Classes)

• Inner classes are a security mechanism in


Java.
– Inner Class
– Method-local Inner Class
– Anonymous Inner Class
Inner class
Accessing the Private Members
Method-local Inner Class
Anonymous Inner Class
static
• is used for memory management mainly.
• static can be:
– Variable (also known as a class variable)
– Method (also known as a class method)
– Block
– Nested class
• Any variable, declared as static, known as a static variable.
• The static variable can be used to refer to the common
property of all objects
• Eg:- 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 :- It makes your program memory efficient
(i.e., it saves memory).
• Java static property is shared to all objects.
Program of the counter without static
variable
Program of the counter with static variable
Java static method
• It can be invoked without the need for
creating an instance of a class.
• It can access static data member and can
change the value of it.
Java static block
Garbage collection
• The programmer need not to care for all those
objects which are no longer in use. Garbage
collector destroys these objects.
• Garbage collector is best example of Daemon
thread as it is always running in background.
• Main objective of Garbage Collector is to free
heap memory by destroying unreachable objects
(no reference of the object).
• EX. Gc(), finalize().
Finalize
• Just before destroying an object, Garbage Collector calls
finalize() method on the object to perform cleanup activities.
• Once finalize() method completes, Garbage Collector
destroys that object.
• finalize() method is present in Object class with following
prototype.
protected void finalize() throws Throwable
• Depends on our requirement, we can override finalize()
method for perform our cleanup activities like closing
connection from database.
Inheritance
• Inheritance in Java is a mechanism in which
one object acquires all the properties and
behaviors of a parent object.
• It is an important concept in OOPs
• It ensures Method overriding and Code
Reusability
• Class: A class is a group of objects which have common
properties. It is a model from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other
class. It is also called a derived class, extended class, or child
class.
• Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a
parent class.
• Reusability: Reusability is a mechanism which enables you to
reuse the fields and methods of the existing class when you
create a new class. You can use the same fields and methods
already defined in the previous class.
Syntax for Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
Types of inheritance
• There can be three types of inheritance in
java:
– single
– multilevel
– hierarchical.
• In java programming, multiple and hybrid
inheritance is supported through interface
only.
Single
Multilevel
Hierarchical
Multiple
Hybrid
Single Inheritance(fields based)
Single inheritance(method based)
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Super Keyword in Java

• The super keyword in Java is a reference


variable which is used to refer immediate
parent class object.
• Usage of Java super Keyword
• super can be used to refer immediate parent
class instance variable.
• super can be used to invoke immediate parent
class method.
• super() can be used to invoke immediate
parent class constructor.
super is used to refer immediate parent class instance variable
super can be used to invoke parent class method
super is used to invoke parent class constructor
ABSTRACT CLASS:

An abstract class is a class that is declared abstract—it


may or may not include abstract methods. Abstract
classes cannot be instantiated, but they can be sub
classed.
An abstract method is a method that is declared
without an implementation (without braces, and
followed by a semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);


• Rules:
– Abstract class must be inherited.
– Abstract methods must be declared, not defined.
– Abstract methods must be overridden in the
subclass.
Example
Interface

• An interface is a collection of abstract methods.


A class implements an interface, thereby
inheriting the abstract methods of the interface.
• An interface is not a class. Writing an interface is
similar to writing a class, but they are two
different concepts. A class describes the
attributes and behaviors of an object. An
interface contains behaviors that a class
implements.
All the methods of the interface need to be
defined in the class WHICH IMPLEMENTS THE
INTERFACE.
Interface Example
Interface example
interface Bank{  
float rateOfInterest();  
}  
class SBI implements Bank{  
public float rateOfInterest()
{
return 9.15f;
}  
}  
class PNB implements Bank{  
public float rateOfInterest()
{
return 9.7f;
}  
}  
class TestInterface2{  
public static void main(String[] args){  
Bank b=new SBI();  
System.out.println("ROI: "+b.rateOfInterest());  
}}  
Multiple interface in Java
interface Printable
{  
void print();  
}  

interface Showable
{  
void show();  
}  

class A7 implements Printable,Showable{  
public void print()
{
System.out.println("Hello");
}  
public void show()
{System.out.println("Welcome");
}  
  
public static void main(String args[]){  
A7 obj = new A7();  
obj.print();  
obj.show();  
 }  
}  
• A class can implement more than one
interface.
• Multiple inheritance can be implemented by
interface.
• Interface can be inherited another interface
• Also implement the methods from parent
interface if you are implement sub interface
Packages

• A java package is a group of similar types of


classes, interfaces and sub-packages.
• Package in java can be categorized in two form,
built-in package and user-defined package.
• There are many built-in packages such as java,
lang, awt, javax, swing, net, io, util, sql etc.
• Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
• Java package provides access protection.
package mypack;
public class abc{
public static void main(String args[]){
System.out.println("Welcome to Package");
}
}
• There are three ways to access the package
from outside the package.
• import package.*;
• import package.classname;
• fully qualified name.
• Using packagename.*
Using packagename.classname
Using fully qualified name

If you use fully qualified name then only


declared class of this package will be accessible.
Now there is no need to import. But you need
to use fully qualified name every time when you
are accessing the class or interface.
Wrapper classes in Java

• The wrapper class in Java provides the


mechanism to convert primitive into object and
object into primitive.
• Int i=5;
• Interger iobj=new Interger(i)//wrapping

• Int j=6;
• Int j=iobj.intvalue();un wrapping
Autoboxing in Wrapper Class
• Unboxing in Wrapper Class
• Unboxing is used to convert the Wrapper
class object into corresponding primitive data
types.
Enhanced For Loop
• Syntax

array - an array or a collection


item - each item of array/collection is assigned
to this variable
dataType - the data type of the
array/collection

You might also like