Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 60

Unit-I

Introduction to JAVA
Different Programming Paradigms

• Functional/procedural programming:
– program is a list of instructions to the
computer

• Object-oriented programming
– program is composed of a collection objects
that communicate with each other
Why Java ?
• Portable
• Easy to learn

• [ Designed to be used on the Internet ]


JVM

• JVM stands for


Java Virtual Machine

• Unlike other languages, Java “executables”


are executed on a CPU that does not exist.
Platform Dependent

myprog.c myprog.exe
gcc machine code
C source code

OS/Hardware

Platform Independent

myprog.java myprog.class
javac bytecode
Java source code

JVM

OS/Hardware
08/22/2021
Hello World
Hello.java
class Hello {
public static void main(String[] args) {
System.out.println(“Hello World !!!”); }
}

C:\javac Hello.java ( compilation creates Hello.class )

C:\java Hello (Execution on the local JVM)


Java OOP concepts
Object Oriented Programming is a paradigm that
provides many concepts such as
-Object
–Class
–Inheritance
–Polymorphism
–Abstraction
–Encapsulation

08/22/2021 8
An object is a thing. A class is a category of things.

8/22/21
8/22/21
8/22/21
Object
Any entity that has state and behavior is known as an object.
For example: chair, pen, table, keyboard, bike etc. It can be
physical and logical.
Object can be defined as an instance of a class. An object
contains an address and takes up some space in memory.
Objects can communicate without knowing details of each
other's data or code, the only necessary thing is that the type
of message accepted and type of response returned by the
objects.
Example: A dog is an object because it has states i.e. color,
name, breed etc. as well as behaviors i.e. wagging the tail,
barking, eating etc.
08/22/2021 12
Creating Objects

Object creation is a three step process,


• Declaration - Giving a name to the object to be
created.
• Instantiation - The new keyword and
constructor creates a instance of the object.
• Initialization - The values will be initialized using
the constructor.

8/22/21 Dept. of SCD / JAVA 13/50


Creating Objects
This program creates a employee object and invokes the calculateSalary
method on the object

8/22/21
Class
• Collection of objects is called class.
• It is a logical entity.
• A class can also be defined as a blueprint from
which you can create an individual object.
• Class does not store any space.
A 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.
08/22/2021 15
Instance variables 
Instance variables are variables within a
class but outside any method. These variables
are initialized when the class is instantiated.
Instance variables can be accessed from
inside any method, constructor or blocks of
that particular class.
Class variables 
Class variables are variables declared
within a class, outside any method, with the
static keyword.
08/22/2021 16
Types of Classes

8/22/21 Dept. of SCD / JAVA 17/50


Structure of a Class

The body of the class contains,


• Variables – This is a container for storing class data.
• Methods – Application behavior implemented and this changes the
data (variables values).

8/22/21 Dept. of SCD / JAVA 18/50


Example: Java Class and Objects

class Lamp {
boolean isOn;
 void turnOn() {
isOn = true;
}
 void turnOff() {
isOn = false;}
 void displayLightStatus() {
 System.out.println("Light on? " + isOn);
}}
 class ClassObjectsExample {
public static void main(String[] args) {
 Lamp l1 = new Lamp(), l2 = new Lamp();
 l1.turnOn();
l2.turnOff();
 l1.displayLightStatus();
l2.displayLightStatus();}}
 
Output:
Light on? true
Light on? False
In the above program,
• Lamp class is created.
• The class has an instance variable isOn and three
methods turnOn(), turnOff() and displayLightStatus().
• Two objects l1 and l2 of Lamp class are created in
the main() function.
• Here, turnOn() method is called using l1 object: l1.turnOn();
• This method sets isOn instance variable of l1 object to true.
• And, turnOff() method is called using l2 object: l2.turnOff();
Methods
• A Java method defines a group of statements as
performing a particular operation
• static indicates a static or class method
• A method that is not static is an instance method
• All method arguments are call-by-value
– Primitive type: value is passed to the method
– Method may modify local copy but will not affect caller’s
value
– Object reference: address of object is passed
– Change to reference variable does not affect caller
– But operations can affect the object, visible to caller
Example Program:
class Main

public static void main(String[] args)
{
System.out.println("About to encounter a method.");
myMethod(); // method call
System.out.println("Method was executed successfully!");
}
private static void myMethod() // method definition
{
System.out.println("Printing from inside myMethod()!");
}
}
Output:
About to encounter a method.
Printing from inside myMethod().
Method was executed successfully!

The method myMethod() in the above program doesn't


accept any arguments. Also, the method doesn't return any
value (return type is void).
Note that, we called the method without creating object
of the class. It was possible because myMethod() is static.
Messages
• Objects communicate with one another by sending
messages. A message is a method call from a message-
sending object to a message-receiving object.
• A message sending object is a sender while a message-
receiving object is a receiver.
•An object responds to a message by executing one of its
methods. Additional information, known as arguments,
may accompany a method call.
• Parameterization allows for added flexibility in message
passing.
•The set of methods collectively defines the dynamic
behavior of an object. An object may have as many
methods as required.
Message Components
A message is composed of three components: 1. An
object identifier that indicates the message
receiver,
2. A method name (corresponding to a method of
the receiver), and
3. arguments (additional information required for
the execution of the method).
Example:
Benjamin as an Object
Attributes:
name = Benjamin
address = 1, Robinson Road
budget = 2000 Methods:
purchase() {
Sean.takeOrder("Benjamin", "sofa", "1, Robinson Road", "12 November")
} getBudget()
{
return budget
}
 
The message Sean.takeOrder(who, stock, address, date) is interpreted as follows:
• Sean is the receiver of the message;
• takeOrder is a method call on Sean;
Benjamin", "stock", "address", "date" are arguments of the message.
Abstraction
• Abstraction is a process where you show
only “relevant” data and “hide” unnecessary
details of an object from the user.
• For example, when you login to your bank
account online, you enter your user_id and
password and press login, what happens
when you press login, how the input data
sent to server, how it gets verified is all
abstracted away from the you
Encapsulation
• Encapsulation simply means binding object
state(fields) and behavior(methods)
together.
• If you are creating class, you are doing
encapsulation.
Program:
class EmployeeCount
{
private int numOfEmployees = 0;
public void setNoOfEmployees (int count)
{
numOfEmployees = count;
}
public double getNoOfEmployees ()
{
return numOfEmployees;
}}
public class EncapsulationExample
{
public static void main(String args[])
{
EmployeeCount obj = new EmployeeCount ();
obj.setNoOfEmployees(5613);
System.out.println("No Of Employees: "+
(int)obj.getNoOfEmployees());}}
Output:
No Of Employees: 5613

The class EncapsulationExample that is using


the Object of class EmployeeCount will not able
to get the No Of Employees directly.
It has to use the setter and getter methods of
the same class to set and get the value.
Inheritance
• The process by which one class acquires the properties
and functionalities of another class is called inheritance.
• Inheritance provides the idea of reusability of code and
each sub class defines only those features that are unique
to it, rest of the features can be inherited from the parent
class.
1. Inheritance is a process of defining a new class
based on an existing class by extending its common data
members and methods.
2. Inheritance allows us to reuse of code, it improves
reusability in your java application.
3. The parent class is called the base class or super
class. The child class that extends the base class is called
the derived class or sub class or child class.
Syntax:
To inherit a class we use extends keyword. Here class A
is child class and class B is parent class.
class A extends B
{
}
Inheritance Example:
class Teacher
{
String designation = "Teacher";
String college = "Beginnersbook"; Output:
void does() Beginnersbook
{ Teacher
Maths
System.out.println("Teaching"); Teaching
}}
public class MathTeacher extends Teacher
{
String mainSubject = "Maths";
public static void main(String args[])
{
MathTeacher obj = new MathTeacher();
System.out.println(obj.college);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();}}  
Types of inheritance:
• Single Inheritance: refers to a child and parent class
relationship where a class extends the another class.
• Multilevel inheritance: refers to a child and parent class
relationship where a class extends the child class. For
example class A extends class B and class B extends class
C.
• Hierarchical inheritance: refers to a child and parent class
relationship where more than one classes extends the
same class. For example, class B extends class A and class
C extends class A.
• Multiple Inheritance: refers to the concept of one class
extending more than one classes, which means a child
class has two parent classes. Java doesn’t support multiple
inheritance
Abstract class in Java
• A class which is declared as abstract is known as
an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method
implemented. It cannot be instantiated.
• An abstract class must be declared with an abstract
keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not
to change the body of the method.
Like C++, in Java, an instance of an abstract class cannot be created, we can
have references of abstract class type though.
abstract class Base {
    abstract void fun();
}
class Derived extends Base {
    void fun() { System.out.println("Derived fun() called"); }
}
class Main {
    public static void main(String args[]) { 
   // Uncommenting the following line will cause compiler error as the 
  // line tries to create an instance of abstract class.
 // Base b = new Base();
  // We can have references of Base type.
Base b = new Derived();
b.fun(); 
}
} Output:
Derived fun() called
Polymorphism
Polymorphism is a object oriented programming feature
that allows us to perform a single action in different ways.
For example, lets say we have a class Animal that has a
method animalSound(), here we cannot give
implementation to this method as we do not know which
Animal class would extend Animal class.
So, we make this method abstract like this:
public abstract class Animal
{
...
public abstract void animalSound();
}
Types of polymorphism:
1) Static Polymorphism
2) Dynamic Polymorphism
Static Polymorphism:
Polymorphism that is resolved during compiler
time is known as static polymorphism. Method
overloading can be considered as static
polymorphism.
Example:- Method Overloading: This allows us to
have more than one methods with same name in a
class that differs in signature.
Program:
class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
public class ExampleOverloading
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:
a
a 10
When I say method signature I am not talking about
return type of the method.
For example,
if two methods have same name, same parameters and
have different return type, then this is not a valid method
overloading example. This will throw compilation error.
Dynamic Polymorphism
It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a
process in which a call to an overridden method is resolved at runtime rather,
thats why it is called runtime polymorphism.
Example
class Animal{
public void animalSound(){
System.out.println("Default Sound");
}
}
public class Dog extends Animal{
public void animalSound(){
System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.animalSound();
}
}
Output:
Woof
Since both the classes, child class and parent class have
the same method animalSound. Which of the method will be
called is determined at runtime by JVM.
Access Control Or Access specifier
• public member (function/data)
– Can be called/modified from outside.
• protected
– Can be called/modified from derived classes
• private
– Can be called/modified only from the current class
• default ( if no access modifier stated )
– Usually referred to as “Friendly”.
– Can be called/modified/instantiated from the same package.
1.Private:
Private members of class in not accessible
anywhere in program these are only accessible
within the class. Private are also called class level
access modifiers.
Example
class Hello
{
private int a=20;
private void show()
{
System.out.println("Hello java");
}}
public class Demo Output:
{ Hello java
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a); //Compile Time Error, you can't access private
data
obj.show(); //Compile Time Error, you can't access private methods
}}
Public:
Public members of any class are accessible anywhere in the program in the
same class and outside of class, within the same package and outside of the
package. Public are also called universal access modifiers.
Example Program:
class Hello
{
public int a=20;
public void show()
{
System.out.println("Hello java"); Output:
} 20
} Hello Java
public class Demo
{
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a);
obj.show();
}
}
 
Protected:
Protected members of the class are accessible within the same class
and another class of the same package and also accessible in inherited
class of another package. Protected are also called derived level access
modifiers.
Example Program:
// save A.java
package pack1;
public class A
{
protected void show()
{
System.out.println("Hello Java");
} }
//save B.java package pack2;
import pack1.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.show();
} }  
Output
Hello Java

In the above example we have created two packages


pack1 and pack2. In pack1, class A is public so we can access
this class outside of pack1 but method show is declared as a
protected so it is only accessible outside of package pack1
only through inheritance.
Default:
Default members of the class are accessible only within
the same class and another class of the same package. The
default are also called package level access modifiers.
Example Program:
//save by A.java package pack;
class A Output
{ Hello Java
void show()
{System.out.println("Hello Java");
} }
//save by B.java package pack2; import pack1.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error, can't access outside
the package
obj.show(); //Compile Time Error, can't access outside the
package
} }  
Static Members
The class level members which have static
keyword in their definition are called static
members.

08/22/2021 51
• Member data - Same data is used for all the
instances (objects) of some Class.
Assignment performed
Class A {
on the first access to the
public int y = 0;
Class.
public static int x_ = 1;
Only one instance of ‘x’
};
exists in memory
A a = new A();
A b = new A(); a b
System.out.println(b.x_); Output: 0 0
a.x_ = 5; y y
System.out.println(b.x_);
A.x_ = 10;
1
System.out.println(b.x_); 5 1
10 A.x_
• Member function
– Static member function can access only static members
– Static member function can be called without an
instance.
Class TeaPot {
private static int numOfTP = 0;
private Color myColor_;
public TeaPot(Color c) {
myColor_ = c;
numOfTP++;
}
public static int howManyTeaPots()
{ return numOfTP; }

// error :
public static Color getColor()
{ return myColor_; }
}
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is
called when an instance of the object is created, and memory is allocated
for the object.
It is a special type of method which is used to initialize the object.
When is a constructor called
Every time an object is created using new() keyword, at least one
constructor is called. It calls a default constructor.
Note: It is called constructor because it constructs the values at the time
of object creation. It is not necessary to write a constructor for a class. It
is because java compiler creates a default constructor if your class
doesn't have any.
Rules for creating Java constructor
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
1. Default constructor (no-arg constructor)
A constructor is called "Default Constructor" when it doesn't have any parameter.
Example of default constructor
//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();  
}  }  
In this example, we are creating the no-arg
constructor in the Bike class. It will be invoked at the
time of object creation.
Output:
Bike is created

2. Parameterized constructor :
A constructor which has a specific number of
parameters is called a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide
different values to the distinct objects. However, you
can provide the same values also.
Example Program:
//Java Program to demonstrate the use of parameterized constructor  
class Student4
{  
    int id;  
    String name;  
    //creating a parameterized constructor  
    Student4(int i,String n){  
    id = i;  
    name = n;   Output:
    }   111 Karan
    //method to display the values   222 Aryan
    void display(){System.out.println(id+" "+name);}  
   
    public static void main(String args[]){  
    //creating objects and passing values  
    Student4 s1 = new Student4(111,"Karan");  
    Student4 s2 = new Student4(222,"Aryan");  
    //calling method to display the values of object  
    s1.display();  
    s2.display();  
   }  }  
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.
•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.
Advantage of Garbage Collection
•It makes java memory efficient because garbage collector
removes the unreferenced objects from heap memory.
•It is automatically done by the garbage collector(a part of JVM)
so we don't need to make extra efforts.
 
08/22/2021 58
finalize() method
 Before an object is garbage collected, the runtime system invokes the objects finalize()
method.
 The finalize() can be used to perform clean up activities such as release system file
resources (or) close sockets (or) close database connections etc.
 The finalize() method is declared in the java.lang.Object class,
Example
protected void finalize(){
//close resource }

Note :It is important to understand that finalize() is only invoked prior to


garbage collection. It is not invoked immediately when an object goes out-of-
scope. So programmers should provide other means of releasing system
resources used by the object. It must not rely on finalize() for normal
program operation.
59
16/1
608/22/2021

You might also like