Nothing Special   »   [go: up one dir, main page]

UNIT-1 Introduction To OOP and Java

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

UNIT 1

INTRODUCTION TO OOP AND JAVA

by
S.Sakkaravarthi, AP/IT
Ramco Institute of Technology, Rajapalayam
Programming Paradigms

• Programming paradigm is an approach to solve problem using


some programming language.
• The high-level programming languages are broadly
categorized into two categories

 Procedure oriented programming(POP) language. E.g., C


 Object oriented programming(OOP) language. E.g., C++, Java
Procedure Oriented Programming Languages
◆ Procedure oriented programming basically consist of writing a list of instruction for the
computer to follow and organizing these instruction into groups known as functions.

◆ procedural programming paradigm characterizes a program as a series of linear steps (that is, code).
This process-oriented model can be thought of as code acting on data. Example: C Programming
language

The disadvantage of the procedure oriented programming languages is:


1. Global data access
2. It does not model real word problem very well
3. No data hiding
Object Oriented Programming Languages

◆ Object-oriented programming (OOP) is a computer programming model that organizes


software design around data, or objects, rather than functions and logic.

◆ An object can be defined as a data field that has unique attributes and behavior.
OOP-Contd
 Object-oriented programming organizes a program around its data (that is, objects) and a set of well-defined
interfaces to that data. An object oriented program can be characterized as data controlling access to code.

 In other words, Object Oriented Programming Paradigm can be defined as a programming model which is
based upon the concept of objects. Objects contain data in the form of attributes and code in the form of
methods.

 For example, dogs have states or data members like color, breed, and the behaviors or methods (actions they
can perform) are barking, wagging their tail, eating, sleeping, etc.
Difference between Procedure Oriented & Object Oriented
Programming Object Oriented Programming
Procedure Oriented Programming

1 program is divided into small parts called functions. program is divided into parts called objects.

2 Importance is not given to data but to functions as well as Importance is given to the data rather than procedures
sequence of actions to be done. or functions because it works as a real world.

3 follows Top Down approach. OOP follows Bottom Up approach.

4 It does not have any access specifier. Data can move freely OOP has access specifiers named Public, Private,
from Protected, etc.
function to function in the system.

5 Data can move freely from function to function in the system. objects can move and communicate with each
other through member functions.

6 To add new data and function in POP is not so easy. OOP provides an easy way to add new data and
function.
7 Most function uses Global data for sharing that can be In OOP, data can not move easily function to
accessed freely from function to function in the system. function, it can be kept public or private so we can
control the access of data.

8 It does not have any proper way for hiding data so it is less OOP provides Data Hiding so provides more security
secure.
9 Overloading is not possible. In OOP, overloading is possible in the form
of Method Overloading and Method
Overriding.

10 Example : C, VB, FORTRAN, Pascal Example : C++, JAVA, PYTHON


Object-oriented programming Paradigm
• Object-oriented programming System(OOPs) is a programming
paradigm based on the concept of “objects” that contain data and
methods.
• The primary purpose of object-oriented programming is to increase
the flexibility and maintainability of programs.
• Object oriented programming brings together data and its
behavior(methods) in a single location(object) makes it easier to
understand how a program works.
What is an
Object?
• Object: is a bundle of data and its behavior (often known as
methods).
• Objects have two characteristics: They have states and
behaviors.
• Examples of 1:states and behaviors Example 2:
Example
Object: House Object: Car
State: Address, Color, Area State: Color, Brand, Weight, Model
Behavior: Open door, close door Behavior: Break, Accelerate, Slow Down,
Gear change.
What is a class?
Class: A class defines the structure and behavior (data and code) that will be shared by a set of objects.

A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. Thus, a class is a logical construct. It can't be physical. Only object has physical reality.

A class can contain fields, Methods, Constructors ,Blocks

Syntax

class <class_name>

field;

method;

}
What is an Object?
Con…
class House {
String address;
String color;
double area;
void openDoor() {
//Write
code here
}
void closeDoor() {
//Write
code here
}
... ...
}
Object Oriented Programming features

Abstraction Encapsulation

Inheritance Polymorphism
Abstractio
n
• One of the most fundamental concept of OOPs is 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 Amazon account online, you enter your
user_id and password and press login, what happens when you
press login, how the input data sent to amazon server, how it gets
verified is all abstracted away from the you.
Abstraction
Con…
• Another example of abstraction:
• A car in itself is a well-defined object, which is composed of several other
smaller objects like a gearing system, steering mechanism, engine, which are
again have their own subsystems. But for humans car is a one single object,
which can be managed by the help of its subsystems, even if their inner
details are unknown.
Object Oriented Programming features

Abstraction Encapsulation

Inheritance Polymorphism
Encapsulatio
n
• Encapsulation simply means binding object state(fields) and
behavior(methods) together. If you are creating class, you are doing
encapsulation.
• Encapsulation is:
• Binding the data with the code that manipulates it.
• It keeps the data and the code safe from external interference
Object Oriented Programming features

Abstraction Encapsulation

Inheritance Polymorphism
Inheritance
• Inheritance is the mechanism by which an object acquires the
some/all properties of another object.
• The process by which one class acquires the properties(data
members) and functionalities(methods) of another class is called
inheritance.
Inheritance
• The aim of inheritance is to provide the reusability of code so that a
class has to write only the unique features and rest of the common
properties and functionalities can be extended from the another
class.
Inheritance
• Inheritance is a process of defining a new class based on an existing
class by extending its common data members and methods.
• Inheritance allows us to reuse of code, it improves reusability in your
java application.
• Note: The biggest advantage of Inheritance is that the code that is
already present in base class need not be rewritten in the child class.
Types of Inheritance
Example Program-Single Level Inheritance
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
Output:
barking…
Eating…
Child and Base
Class
• Child Class:
• The class that extends the features of another class is known as child class,
sub class or derived class.

• Parent Class:
• The class whose properties and functionalities are used(inherited) by
another class is known as parent class, super class or Base class.

• Note: The derived class inherits all the members and methods that
are declared as public or protected.
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 C extends class B and class
B extends class A.
• Hierarchical inheritance: refers to a child and parent class relationship
where more than one classes extends the same class. For example, classes
B, C & D extends the same 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. For
example class C extends both classes A and B. Java doesn’t support
multiple inheritance
Object Oriented Programming features

Abstraction Encapsulation

Inheritance Polymorphism
Polymorphis
m
• Polymorphism is one of the OOPs feature that allows us to perform a
single action in different ways.

• Polymorphism is the capability of a method to do different things


based on the object that it is acting upon.
Polymorphis
m
• In other words it means, one method with multiple implementation,
for a certain class of action. And which implementation to be used is
decided at runtime depending upon the situation (i.e., data type of
the object)
Static and Dynamic
Polymorphism
• Polymorphism could be static and dynamic both.
• Method Overloading is static polymorphism while, Method
overriding is dynamic polymorphism.
Static
Polymorphism
• Overloading in simple words means more than one method having
the same method name that behaves differently based on the
arguments passed while calling the method.
• This called static because, which method to be invoked is decided at
the time of compilation.(compile time)
Dynamic
Polymorphism
• Overriding means a derived class is implementing a method of its
super class. The call to overridden method is resolved at runtime,
thus called runtime polymorphism
Features of Object oriented Programming Paradigm

 Bottom–up approach in program design

 Programs organized around objects, grouped in classes

 Focus on data with methods to operate upon object’s data

 Interaction between objects through functions

 Reusability of design through creation of new classes by adding features to


existing classes
Features of Object oriented Programming Paradigm

 Programs are divided into simple elements referred to as object


 Focus is on properties and functions rather than procedure.
 Data is hidden from external functions.
 Functions operate on the properties of an object.
 Objects may communicate with each other through a function called messaging.
 Follow the bottom-up approach in oop design
Advantages of Object oriented Programming (OOP)

 It helps in data hiding, keeping the data and information safe from leaking or
exposure.

 Because OOPs provide reusability to the code, we can use a class many times.

 In OOPs, it is easy to maintain code as there are classes and objects, which help
in making it easy to maintain rather than restructure.
Java Buzzword
The features of Java are also known as Java buzzwords. The primary objective of Java
programming language creation was to make it portable, simple and secure programming language. A list of the
most important features of the Java language is given below.
I) Simple
II) Object Oriented
III) Portable
IV) Platform Independent
V) Secured
VI) Robust
VII)Architecture Neutral
VIII)Interpreted & High Performance
IX) Distributed
X) Dynamic
XI) Multithreaded
Java-Simple
Simple: Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun
Microsystem, Java language is a simple programming language because:

 Java syntax is based on C++ (so easier for programmers to learn it after C++).

 Java has removed many complicated and rarely-used features, for example, explicit pointers, operator
overloading, etc.

 There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.
Java-Object Oriented
 Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we
organize our software as a combination of different types of objects that incorporate both data and behavior.

 Object-oriented programming (OOPs) is a methodology that simplifies software development and


maintenance by providing some rules.

Basic concepts of OOPs are:


1) Object
2) Class
3) Encapsulation
4) Inheritance
5) Polymorphism
6) Abstraction
Java-Portable

Portable

 Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.
Java-Platform Independent
 Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc.

 Java code is compiled by the compiler and converted into bytecode (class file)

 This bytecode or class file is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
Java-Secured

 Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:

 No explicit pointer

 Java Programs run inside a virtual machine sandbox


Java-Robust

 Java uses strong memory management.

 There is a lack of pointers that avoids security problems.

 Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application anymore.

 There are exception handling and the type checking mechanism in Java. All these points make Java robust.
Java-Architecture Neutral

 Java is architecture neutral because there are no implementation dependent features, for example, the size of
primitive types is fixed.

 In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory
for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Java-Interpreted & High Performance

 Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to
native code.

 It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why
it is slower than compiled languages, e.g., C, C++, etc.
Java-Distributed

Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used
for creating distributed applications. This feature of Java makes us able to access files by calling the methods
from any machine on the internet.
Java-Dynamic

 Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on
demand.

 Java supports dynamic compilation and automatic memory management (garbage collection).
Java-Multithreading

Multithreaded

 A thread is like a separate program, executing concurrently. We can write Java programs that deal with many
tasks at once by defining multiple threads.

 The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a
common memory area.

 Threads are important for multi-media, Web applications, etc.


Programming Structures in Java- A Simple Java
Program to display Hello world Message
Class Simple

Public static void main(String args[])

System.out.println(“HELLOWORLD!”);

To compile: javac Simple.java

To execute: java Simple

Output: HELLOWORLD!
Compilation Flow

When we compile Java program using javac tool, the Java compiler converts the
source code into byte code.
At Runtime Flow, the following steps are performed
Explanation
Classloader: It is the subsystem of JVM that is used to load class files.
Bytecode Verifier: Checks the code fragments for illegal code that can violate access rights to objects.
Interpreter: Read bytecode stream then execute the instructions.
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static method. The
main() method is executed by the JVM, so it doesn't require creating an object to invoke the main() method.
So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument.
o System.out.println() is used to print statement. Here, System is a class, out is an object of the
PrintStream class, println() is a method of the PrintStream class.
Defining Classes in java
A class is a template for an object, and an object is an instance of a class. A class is declared by use of the class
keyword
Syntax:
class classname {
type instance- variable1;
type instance- variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
...
type methodnameN(parameter-list) {
// body of method
}
Declaring Objects
 First, declare a variable of the class type. This variable does not define an object. Instead, it is simply a
variable that can refer to an object.
 Second, acquire an actual, physical copy of the object and assign it to that variable. This is done using
the new operator.
 The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns
a reference to it. This reference is then stored in the variable. Thus, in Java, all class objects must be
dynamically allocated.

Syntax:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
Declaring Objects –
contd…

Box mybox; // declare reference to object


mybox = new Box(); // allocate a Box object

The first line declares mybox as a reference to an object of type Box. At this point, mybox does not
yet refer to an actual object. The next line allocates an object and assigns a reference to it to
mybox.

After the second line executes, we can use mybox as if it were a Box object. But in reality,
mybox simply holds, in essence, the memory address of the actual Box object.
Java Program using class and objects
class Box

double width;

double height;

double depth;

class BoxDemo // This class declares an object of type Box.

public static void main(String args[]) {

Box mybox = new Box();

double vol;

mybox.width =10; // assign values to mybox's instance variables

mybox.height = 20;

mybox.depth = 15;

vol = mybox.width * mybox.height * mybox.depth; // compute volume of box

System.out.println("Volume is " + vol);

Output: Volume is 3000.0


Assigning Object Reference
Syntax:

Box b1=new Box();


Box b2=b1;

 b2 is being assigned a reference to a copy of the object referred to by b1.


 b1 and b2 will both refer to the same object.
 It simply makes b2 refer to the same object as does b1
 Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since
they are the same object.
Constructor & Methods
 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.

 Constructor is a special type of method having the same name as class name and it is used to initialize the
object.

 Every time an object is created using the new() keyword, at least one constructor is called.

 It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
provides a default constructor by default.

Rules for creating Java 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 Constructor
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)

2. Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


class <class_name>
{
<class_name>()
{

}
}
Default Constructor
Example of default-constructor:
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.
1. //Java Program to create and call a default constructor
2. class Bike1{
3. Bike1() //creating a default constructor
4. {
5. System.out.println("Bike is created");
6. }
7. public static void main(String args[]) //main method
8. {
9. //calling a default constructor
10. Bike1 b=new Bike1();
11. }
12. }

Output: Bike is created


Default Constructor

If there is no constructor in a class, Compiler automatically creates a default constructor


Example of default constructor that displays the default values
1. class Student{
2. int id;
3. String name;
4. void display() //method to display the value of id and name
5. {System.out.println(id+" "+name);}
6. public static void main(String args[]){
7. Student s1=new Student(); //creating objects
8. Student s2=new Student();
9. s1.display(); //displaying values of the object
10. s2.display();
11. }
12. }
Output: 0 null
0 null
Explanation: In the above class, we are not creating any constructor, so compiler provides a default constructor.
Here 0 and null values are provided by default constructor
Parameterized Constructor
Java Parameterized Constructor: A constructor which has a specific number of parameters is called a
parameterized constructor. The parameterized constructor is used to provide different values to distinct objects.
1. class Student {
2. int id;
3. String name;
4. Student4(int i,String n){
5. id = i;
6. name = n;
7. }
8. void display(){System.out.println(id+" "+name);}
9. public static void main(String args[]){
10. Student4 s1 = new Student4(111,“Raj");
11. Student4 s2 = new Student4(222,“Kumar");
12. s1.display();
13. s2.display();
14. } }
Method in Java
 A method is a block of code or collection of statements or a set of code grouped together to perform a certain
task or operation. It is used to achieve the reusability of code.

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: Public, Private, Protected and Default
Method in Java
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.
Method in Java
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.

Types of Method:
There are two types of methods in Java:
o Predefined Method
o User-defined Method

Predefined Method:

In Java, predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods. 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. Some pre-defined methods are length(),
equals(), compareTo(), sqrt(), etc.
Built-in Method Example Program
1. public class Demo
2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }

Output:

The maximum number is: 9


User defined Method Example Program
The method written by the user or programmer is known as a user-defined method. These methods are modified
according to the requirement.
1. import java.util.Scanner;
2. public class EvenOdd {
3. public static void main (String args[]) {
4. Scanner scan=new Scanner(System.in);
5. System.out.print("Enter the number: ");
6. int num=scan.nextInt();
7. findEvenOdd(num);
8. }}
public static void findEvenOdd(int num)
{
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
Difference between Constructor and Method in Java:

Java Constructor Java Method

A constructor is used to initialize the state of an object. A method is used to expose the behavior of an
object.

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 Java compiler provides a default constructor if you don't have any The method is not provided by the compiler in
constructor in a class. any case.

The constructor name must be same as the class name. The method name may or may not be same as
the class name.
Access Specifier

Access Modifier within class within package outside package by subclass only outside package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
Private-Access Specifier
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
}
Default-Access Specifier
1. package pack;
2. class A{
3. void msg(){System.out.println("Hello");}
4. }
5. //save by B.java
6. package mypack;
7. import pack.*;
8. class B{
9. public static void main(String args[]){
10. A obj = new A();//Compile Time Error
11. obj.msg();//Compile Time Error
12. }
13. }

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.
Protected-Access Specifier
The protected access modifier is accessible within package and outside the package but through inheritance
only.
//save by A.java
package pack;
public class A
{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
1. package mypack;
2. import pack.*;
3. class B extends A{
4. public static void main(String args[]){
5. B obj = new B();
6. obj.msg();
7. }
8. } OUTPUT:Hello
Public-Access Specifier
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
//save by B.java
6. package mypack;
7. import pack.*;
8.
9. class B{
10. public static void main(String args[]){
11. A obj = new A();
12. obj.msg();
13. } }

Output: Hello
RECAP

Constructor & Methods


Difference between Constructor and Method in Java:

Java Constructor Java Method


A constructor is used to initialize the A method is used to expose the
state of an object. behavior of an object.

A constructor must not have a return A method must have a return type.
type.

The constructor is invoked implicitly. The method is invoked explicitly.


Difference between Constructor and Method in Java:

Java Constructor Java Method

The Java compiler provides a default The method is not provided by


constructor if not provided any constructor the compiler in any case.
in a class.

The constructor name must be same as the The method name may or may
class name. not be same as the class name.
Access Specifier/Access Modifier

The access modifiers in Java controls the accessibility or scope


of a field, method, constructor, class.

There are four types of access modifier in java:

1. private
2. default
3. protected
4. public
Access Specifier
Members private default protected public
of Java
class N Y N Y
variable Y Y Y Y
method Y Y Y Y
constructor Y Y Y Y
interface N Y N Y
Access Specifier
Access within within outside package outside
Modifier class package by subclass only package

private Y N N N

default Y Y N N

protected Y Y Y N

public Y Y Y Y
Private-Access Specifier

The Private access modifier is accessible only within the class. It


cannot be accessed from outside the class.
Example:

Create two classes A and Simple. The class A contains private


data member and private method. When accessing these private
members from outside the class (i.e. Simple) , compile-time error will
occur.
Example Program-Private Access Specifier

class A public class Simple


{ {
private int data=40; public static void main(String args[])
private void msg() {
{ A obj=new A();
System.out.println("Hello java"); //Compile Time Error
} System.out.println(obj.data);
} obj.msg();//Compile Time Error
}
}
Default-Access Specifier

 The default modifier is accessible only within package. It


cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than
protected, and public.
 If no access modifier is specified, then it is treated as default
modifier
Default-Access Specifier
In this program, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.

//save by B.java
//save by A.java
package mypack;
package pack;
import pack.*;
class A
class B
{
{
void msg()
public static void main(String args[])
{
{
System.out.println("Hello");
A obj=new A(); //Compile Time Error
}
obj.msg(); //Compile Time Error
}
}
}
Protected -Access Specifier
The protected access specifier is accessible within package and
outside the package but through inheritance only.
//save by B.java
//save by A.java
package mypack;
package pack;
import pack.*;
public class A
class B extends A
{
{
protected void msg()
public static void main(String args[])
{
{
System.out.println("Hello");
B obj=new B();
}
obj.msg(); Output: Hello
}
}
}
Public -Access Specifier
The public access specifier is accessible everywhere. It has
the widest scope among all other modifiers.
//save by B.java
//save by A.java
package mypack;
package pack;
import pack.*;
public class A
class B
{
{
public void msg()
public static void main(String args[])
{
{
System.out.println("Hello");
A obj=new A();
}
obj.msg(); Output: Hello
}
}
}
Static Members
The static keyword in Java is used for memory management
mainly
The static keyword can be applied to a Variable, Methods,
blocks and nested classes

The static can be:


1.Variable (also known as a class variable)
2.Method (also known as a class method)
3.Block
4.Nested class
static variable
The Variable which is declared with static keyword is called 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.
Advantage of Static Variable

It makes java program memory efficient (i.e., it saves


memory).
Static Method
The Method which is declared with static keyword is called static
method.

 A static method belongs to the class rather than the object


of a class.

 A static method can be invoked without the need for


creating an instance of a class.

 A static method can access only static data member and


can change the value of it.
Two main restrictions of Static Method

 The static method can not use non static data member or
call non-static method directly

 this and super cannot be used in static context


Static block

 The static block is used to initialize the static data


member.

 Static block is executed before the main method at the


time of class loading
Example Program-Static block
class staticdemo
{

Static
{
System.out.println(“static block is invoked”); OUTPUT:
}
static block is executed
public static void main(String args[]) Hello Main
{
System.out.println(“Hello Main”);
}
}
Difference between Instance Variable and Static
Instance Variable variable Static Variable
Each object will have its own copy of instance Only one copy of a static variable per class
variable. irrespective of how many objects created.
Changes made in an instance variable using In case of static changes will be reflected in
one object will not be reflected in other other objects as static variables are
objects as each object has its own copy of common to all object
instance variable. of a class.

Instance variable can be accessed through Static Variables can be accessed directly
object references. using class name.
class Hello class Hello
{ {
int a; static int a;
} }
Java Doc Comments

 The java comments are statements that are not executed by


the compiler and interpreter.

 The comments can be used to provide information or explanation


about the variable, method, class or any statement.

 The Comments can be used to provide information or


explanation about the variable, method, class or any
statement.
Types of Comments in java

 Single Line Comment.

 Multi Line Comment

 Documentation Comment
Single Line Comment

 Single Line Comment- Starts with two forward slashes

Used to comment only one line

 Syntax

//This is single line comment


Multi Line Comment

 Multi Line Comment Starts with /* and ends with */

 Any text between /* and */ will be ignored by java

Used to comment only multiple lines of code

 Syntax
/* This is
Multiline comment
*/
Multi Line Comment

 Multi Line Comment Starts with /* and ends with */

 Any text between /* and */ will be ignored by java

Used to comment only multiple lines of code

 Syntax
/* This is
Multiline comment
*/
Documentation Comment
 Documentation comments are usually used to write
large programs for a project or software application as
it helps to create documentation API

 These APIs are needed for reference, i.e., which


classes, methods, arguments, etc., are used in the
code. Javadoc tool is used to create documentation
API

 The documentation comments are placed between


/** and */
References
1. www.javatpoint.com

You might also like