SlideShare a Scribd company logo
Classes and Objects in Java
and
Inheritance in Java
1
Basics of Classes in Java Recap
Contents
 Introduction to classes and objects in Java.
 Understand how some of the OO concepts learnt
so far are supported in Java.
 Understand important feature inheritance in
Java classes.
2
Introduction
 Java is a true OO language and therefore the underlying
structure of all Java programs is classes.
 Anything we wish to represent in Java must be encapsulated
in a class that defines the “state” and “behavior” of the basic
program components known as objects.
 Classes create objects and objects use methods to
communicate between them. They provide a convenient
method for packaging a group of logically related data items
and functions that work on them.
 A class essentially serves as a template for an object and
behaves like a basic data type “int”. It is therefore important
to understand how the fields and methods are defined in a
class and how they are used to build a Java program that
incorporates the basic OO concepts such as encapsulation,
inheritance, and polymorphism.
3
Classes
 A class is a collection of fields (data) and methods
(procedure or function) that operate on that data.
4
Circle
centre
radius
circumference()
area()
Classes
 A class is a collection of fields (data) and methods
(procedure or function) that operate on that data.
 The basic syntax for a class definition:
 Bare bone class – no fields, no methods
5
public class Circle {
// my circle class
}
class ClassName
{
[fields declaration]
[methods declaration]
}
Adding Fields: Class Circle with fields
 Add fields
 The fields (data) are also called the instance
varaibles.
6
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
}
Adding Methods
 A class with only data fields has no life.
Objects created by such a class cannot
respond to any messages.
 Methods are declared inside the body of the
class but immediately after the declaration of
data fields.
 The general form of a method declaration is:
7
type MethodName (parameter-list)
{
Method-body;
}
8
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
r = 2;
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}
}
Method Body
Data Abstraction
Can define variables (objects) of that type:
Circle aCircle;
Circle bCircle;
Circle aCircle = new aCircle();
Circle bCircle=new bCircle():
9
Data abstraction is the
reduction of a particular body
of data to a simplified
representation of the whole
Class of Circle cont.
 aCircle, bCircle simply refers to a Circle object,
not an object itself.
10
aCircle
Points to nothing (Null Reference)
bCircle
Points to nothing (Null Reference)
null null
11
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
Creating objects of a class
 Objects are created dynamically using the new
keyword.
 aCircle and bCircle refer to Circle objects
 Circle aCircle;
12
bCircle = new Circle() ;
aCircle = new Circle() ;
13
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
P
aCircle
Q
bCircle
Before Assignment
P
aCircle
Q
bCircle
Before Assignment
Automatic garbage collection
 The object does not have a reference and cannot
be used in future.
 The object becomes a candidate for automatic
garbage collection.
 Java automatically collects garbage periodically
and releases the memory used to be used in the
future.
14
Accessing Object/Circle Data
 Similar to C syntax for accessing data defined in
a structure.
15
Circle aCircle = new Circle();
aCircle.x = 2.0 // initialize center and radius
aCircle.y = 2.0
aCircle.r = 1.0
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
Executing Methods in Object/Circle
 Using Object Methods:
16
Circle aCircle = new Circle();
double area;
aCircle.r = 1.0;
area = aCircle.area();
sent ‘message’ to aCircle
Using Circle Class
// Circle.java: Contains both Circle class and its user
class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data
field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking
method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+"
Area="+area);
System.out.println("Radius="+aCircle.r+"
Circumference ="+circumf);
}
}
17
java MyMain
Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}
}
Inheritance in Java
 It is the mechanism in java by which one class is
allow to inherit the features(fields and methods)
of another class.
class ClassName [extends SuperClassName]
{
[fields declaration]
[methods declaration]
}
18
Important terminology:
 Super Class: The class whose features are inherited is
known as super class(or a base class or a parent class).
 Sub Class: The class that inherits the other class is known
as sub class(or a derived class, extended class, or child
class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
 Reusability: Inheritance supports the concept of
“reusability”, i.e. when we want to create a new class and
there is already a class that includes some of the code that
we want, we can derive our new class from the existing
class. By doing this, we are reusing the fields and methods
of the existing class.
19
Inheritance
20
 The keyword used for inheritance is extends.
Syntax :
 class derived-class extends base-class { //methods
and fields }
21
Types of Inheritance in Java
 Single Inheritance :
In single inheritance, subclasses inherit the features of
one superclass. In image below, the class A serves as
a base class for the derived class B.
22
Example
//Java program to illustrate the
// concept of single inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
class two extends one
{
public void print_for()
{
System.out.println("for");
}
}
// Driver class
public class Main
{
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
23
Multilevel Inheritance
 In Multilevel Inheritance, a derived class will be inheriting a
base class and as well as the derived class also act as the base
class to other class. In below image, the class A serves as a base
class for the derived class B, which in turn serves as a base class
for the derived class C. In Java, a class cannot directly access the
grandparent’s members.
24
Multilevel Inheritance
25
Example for multilevel Inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
class two extends one
{
public void print_for()
{
System.out.println("for");
}
}
class three extends two
{
public void print_geek()
{
System.out.println("Geeks");
}
}
// Drived class
public class Main
{
public static void main(String[]
args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}
26
Hierarchical Inheritance :
 In Hierarchical Inheritance, one class serves as a superclass (base
class) for more than one sub class.In below image, the class A
serves as a base class for the derived class B,C and D.
27
// Java program to illustrate the
// concept of Hierarchical inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
class two extends one
{
public void print_for()
{
System.out.println("for");
}
}
class three extends one
{
/*............*/
}
// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
two t = new two();
t.print_for();
g.print_geek();
}
}
28
Multiple Inheritance (Through
Interfaces)
 In Multiple inheritance ,one class can have more than one superclass and
inherit features from all parent classes. Please note that Java does not
support multiple inheritance with classes. In java, we can achieve multiple
inheritance only through Interfaces. In image below, Class C is derived from
interface A and B.
29
Multiple Inheritance (Through
Interfaces)
30
Example of Multiple Inheritance
// Java program to illustrate the
// concept of Multiple inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
interface one
{
public void print_geek();
}
interface two
{
public void print_for();
}
interface three extends one,two
{
public void print_geek();
}
class child implements three
{
@Override
public void print_geek() {
System.out.println("Geeks");
}
public void print_for()
{
System.out.println("for");
}
}
// Drived class
public class Main
{
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();
c.print_geek();
}
}
31
Hybrid Inheritance(Through
Interfaces)
 It is a mix of two or more of the above types of
inheritance. Since java doesn’t support multiple
inheritance with classes, the hybrid inheritance
is also not possible with classes. In java, we can
achieve hybrid inheritance only through
Interfaces.
32
Hybrid Inheritance(Through
Interfaces)
33
Advantages of Inheritance
 Reusability -- facility to use public methods of base class
without rewriting the same
 Extensibility -- extending the base class logic as per business
logic of the derived class
 Data hiding -- base class can decide to keep some data private so
that it cannot be altered by the derived class
 Overriding -- With inheritance, we will be able to override the
methods of the base class so that meaningful implementation
of the base class method can be designed in the derived class.
34
Method Overloading
 If a class has multiple methods having same
name but different in parameters, it is known
as Method Overloading.
 It is also known as Compile-Time Polymorphism
35
Overloading
 If we have to perform only one operation, having
same name of the methods increases the
readability of the program
36
Overloading
 Different ways to overload the method
There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
37
Overloading
 1) Method Overloading: changing no. of
arguments
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
38
Overloading
 2) Method Overloading: changing data type of
arguments
class Adder{
int add(int a, int b){return a+b;}
double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
Adder ob1= new Adder();
Ob1.add(11,11);
Ob1.add(11,12.6);
//System.out.println(Adder.add(11,11));
//System.out.println(Adder.add(12.3,12.6));
}}
39
Method Overriding
 If subclass (child class) has the same method as
declared in the parent class, it is known
as method overriding in Java.
 In other words, If a subclass provides the specific
implementation of the method that has been
declared by one of its parent class, it is known as
method overriding.
40
Overriding
 Overriding is a feature that allows a subclass or
child class to provide a specific implementation
of a method that is already provided by one of its
super-classes or parent classes.
41
Overriding
 When a method in a subclass has the same name,
same parameters or signature, and same return
type(or sub-type) as a method in its super-class,
then the method in the subclass is said to
override the method in the super-class.
42
Overriding
43
Usage of Java Method Overriding
 Method overriding is used to provide the specific
implementation of a method which is already
provided by its superclass.
 Method overriding is used for runtime
polymorphism
44
 Rules for Java Method Overriding
 The method must have the same name as in the
parent class
 The method must have the same parameter as in the
parent class.
 There must be an IS-A relationship (inheritance).
45
Overriding
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
Bike is running safely 46
Scope of the Variable
Method Scope
Variables declared directly inside a method are
available anywhere in the method following the
line of code in which they were declared.
47
Scope of Variables in Java
 Scope is that area of the program where the variable
is visible to a program and can be used (accessible).
 i.e. the scope of variable determines its accessibility
for other parts of program.
 Java allows declaring variables within any block. A
block defines scope that starts with an opening curly
brace and ends with a closing curly brace.
 There are three types of variables in java,
depending on their scope: local variables, instance
variables, and class variables (static variables).
48
Scope of Variables in Java
 1. Scope of Local Variables in Java
 2. Scope of Instance variables in Java
 3. Scope of Static variables
49
Scope of the method
public class MyClass {
public static void main(String[] args) {
// Code here cannot use x
int x = 100;
// Code here can use x
System.out.println(x);
}
}
50
Block Scope
 A block of code refers to all of the code between
curly braces {}
 Variables declared inside blocks of code are
only accessible by the code between the curly
braces which follows the line in which the
variable was declared.
 A block of code may exist on its own or it may
belong to an if, while or for statement. In the
case of for statements, variables declared in the
statement itself are also available inside the
block's scope.
51
Example Program
public class MyClass {
public static void main(String[] args) {
// Code here CANNOT use x
{ // This is a block
// Code here CANNOT use x
int x = 100;
// Code here CAN use x
System.out.println(x);
} // The block ends here
// Code here CANNOT use x
}
}
52
Java Modifiers
Modifiers divided into two groups:
Access Modifiers - controls the access level
Non-Access Modifiers - do not control access level,
but provides other functionality
53
The four primary access modifiers
in Java are:
 Default access modifier
 Protected access modifier
 Public access modifier
 Private access modifier
54
Access Modifiers
For classes, we can use either public or default
public :The class is accessible by any other class
default :The class is only accessible by classes in the
same package. This is used when you don't specify a
modifier.
//You will learn more about packages in the Packages
chapter
55
Access Modifiers
For attributes, methods and constructors, you can
use one of the following:
public :The code is accessible for all classes
private :The code is only accessible within the declared
class
default :The code is only accessible in the same package.
This is used when you don't specify a modifier. You will
learn more about packages in the Packages chapter
protected :The code is accessible in the same package and
subclasses. You will learn more about subclasses and
superclasses in the Inheritance chapter
56
Non-Access Modifiers
For classes, we can use either final or abstract:
final:The class cannot be inherited by other classes
abstract :The class cannot be used to create objects (To
access an abstract class, it must be inherited from
another class. You will learn more about inheritance
and abstraction in the Inheritance and Abstraction
chapters)
57
Non Access Modifiers
final Attributes and methods cannot be overridden/modified
static Attributes and methods belongs to the class, rather than an object
abstract
Can only be used in an abstract class, and can only be used on methods.
The method does not have a body, for example abstract void run();. The
body is provided by the subclass (inherited from). You will learn more
about inheritance and abstraction in the Inheritance and Abstraction
chapters
transient
Attributes and methods are skipped when serializing the object
containing them
synchronize
d
Methods can only be accessed by one thread at a time
volatile
The value of an attribute is not cached thread-locally, and is always read
from the "main memory" 58
Access Modifiers
59
Access Modifiers
60
Java Package
 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.
61
Java Packages
 There are many built-in packages such as java,
lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package
 Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
 Java package provides access protection.
 Java package removes naming collision.
62
Java Packages
63
Syntax to create packages
package nameOfPackage;
64
Java Packages
Consider the following package program in Java:
package pack;
public class A
{ public void msg()
{System.out.println("Hello");
}
}
65
Java Packages
package mypack;
import pack.*;
class B{
public static void main(String args[])
{ A obj = new A();
obj.msg();
}
}
67
Access Modifiers
68
69
Default access modifiers
 The default access modifier is accessible to any
package by default. The programmers need not
specify any keyword to use the default access
modifier.
 It means that the programmer doesn’t need to specify
a class, method, or constructor default explicitly.
 A class or method is, by default, accessible from any
other “class” that exists in the same package. We
usually don’t define variables and methods with any
access modifier.
70
Example Code
class Def {
int num = 175;
void print() {
System.out.println("Default class " + num);
}
}
public class Test {
public static void main(String args[]) {
Def def = new Def();
def.print();
}
}
Output:
Default class 175
71
Private access modifiers
 As the name suggests, the private access modifier limits
access to the defining “class” only. With the help of the
“private” keyword, we can implement the real concept
of Data Encapsulation. It means to hide the private
members form the outside world.
 The functions labeled as private are accessible within
the class only.
 You can’t declare a top-level class or interface as
private. Also, if so, then it would be useless as no one
could access it.
 The programmer must define a getter or setter to
access private methods or variables.
72
The example below will help you visualize a getter for the private
method:
class Priv {
private void PRINT() {
System.out.println("Private access");
}
public void getPrint() {
PRINT();
}
}
public class Test {
public static void main(String args[]) {
Private priv = new Priv();
priv.PRINT();
}
}
Output:Private access
73
Public access modifiers
 The public modifiers are the most common
in Java applications. They mean that any
public class, method, variable, interface, or
constructor is accessible throughout the
package.
 Before using a public class in another
package, you must first import it.
 If you inherit a public class, then the
subclass will have all its methods and
variables by default.
74
Example Code For Public access
modifier
public class First {
public void print() {
System.out.println("Hello");
}
public class Test extends First {
public static void main(String args[]) {
First first = new First();
first.print();
}
}
Output:Hello
75
Protected access modifiers
 Objects or methods having protected access are
visible to the package and subclasses only.
 The following are a few points to elaborate on the
exact behavior:
 These methods, variables, or constructors are
accessible within the package only and also
available to all the subclasses.
 The protected keyword doesn’t apply to any class or
interface.
 Interface methods or variables can’t have protected
access.
76
Example Code for Protected Access:
public class First {
protected static int count;
public void update(){
System.out.println(++count);
}
public class Test extends First {
public static void main(String args[]) {
First out = new First();
out.update();
}
}
}Output:1
77
Non-access modifiers
 Static – It means something is directly related to a
class.
 Final – It indicates that the object is immutable.
 Abstract – It means you need to subclass for creating
objects.
 Synchronized – It indicates that only one thread can
execute a method at a time.
 Transient – It means to exclude something during
serialization.
 Volatile – It indicates that different threads can modify
a variable’s value.
 Native – It shows that the method is available in the
native code using JNI or JNA.
78
Static Modifier
 Static Modifier is used for creating a static
variable and static method.
 The reserved keyword for a static modifier is
static, which is used before the data type of the
variable or method.
 A static method or variable exists independently
of any class object.
 It means a static variable or static method can
be called using the class name without creating
an instance or object of this class.
79
Static Modifier
 Car.java
public class Car{
public static String msg; //String type static
variable is declared
public static void create(){
System.out.print(msg); //Variable msg is passed as
argument to print.
}
}
80
Static Modifier
Main.java
public class Main
{ //initialization of class
public static void main(String[] args)
{
//value is stored in static variable
Car.msg = "A new car has been created";
// static method in class Car is invoked
Car.create();
}
}
81
Final Modifier
 In Java, variable, method, and class can have a final
non-access modifier. The reserved keyword for a
final non-access modifier is final. This keyword is
used to make any class, method, or variable final.
 Once a final variable is initialized, you cannot change
its value again. A final variable that is uninitialized is
called a blankfinal variable that can be initialized
only in the constructor of a class. To make a class
variable, sometimes, we use the static keyword
with final. If a static final variable is not initialized,
we can initialize it in a static block.
82
Final Modifier
public class Main{ //initialization of class
//declare a final variable of int data type
public final int number = 1;
//non-static method to print number value
public void print(){
System.out.print(number); //print number
number = 2; //change value of number
System.out.print(number); //print new value
}
// main method
public static void main(String[] args){
//object of class Main to access non-static methods
Main p = new Main();
//print method invoked
p.print();
}
} //end of class 83
If we remove code at line 11, the modified code would be executed without
any error.
Code Example for Final Variable:
public class Main{ //initialization of class
//declare a final variable of int data type
public final int number = 1;
//non-static method to print number value
public void print(){
System.out.print("Output is "+number); //print number
}
// main method
public static void main(String[] args){
//object of class Main to access non-static methods
Main p = new Main();
//print method invoked
p.print();
}
} //end of class
84
 Code Example for Static Final Variable:
public class Main{ //initialization of class
//declare a static final variable of int data type
public static final int number = 1;
// main method
public static void main(String[] args){
System.out.print("Output is "+number); //print number
}
} //end of class
 A method that we cannot override is called final method. It can be
inherited in any other class.
85
Code Example for Final Method:
Car.java
public class Car{
//final method
public final void create(){
System.out.print("I'm final method to create a car.");
}
}
Main.java
//initialization of class
public class Main extends Car{
//non-static method to access non-static methods in Car.java
public void makeCar(){
create(); //method invoked
}
// main method
public static void main(String[] args){
Main m = new Main(); //object of Main class
m.makeCar(); //call to makeCar method
} //end of main method
} //end of class
86
A class that we cannot extend is called final class. It means a final class cannot be inherited by any
other class.
 Code Example for Final Class:
Car.java
public final class Car{
//void method
public void print(){
//method body
}
}
Main.java
//initialization of class
public class Main extends Car{
public static void main(String[] args){
} //end of main method
} //end of class
87
Abstract Modifier
 A class or method can be declared as abstract. Reserved keyword abstract is
used for the abstract modifier.
 An abstract class or method cannot be final because an abstract class is made
with the purpose of extending it in other classes and an abstract method is
made for the sole purpose of overriding the method body. To make a class
abstract, at least one abstract method should be defined in a class. If we have to
declare abstract methods in a class, a class must be an abstract class.
 An abstract method is just a declaration; it does not contain an implementation
or method body. You will have to define its implementation by overriding this
method in a class, which has extended the abstract class. When a class extends
an abstract class, all the abstract methods defined in the abstract class must be
overridden in a subclass.
88
Example Code: Abstact Modifier
Car.java
public abstract class Car{
public abstract void create();
public void print(){
System.out.print("I'm not abstract
method.");
}
}
89
Main.java
//initialization of class
public class Main extends Car{
// overriding method defined in Car
class
//as create is only abstract method in
Car class
//overriding it is compulsory
//otherwise error will occur
@Override
public void create(){
System.out.println("I'm overridden
method.");
}
// main method
public static void main(String[] args){
Main m = new Main(); //object of Main
class
m.create(); //invoking overridden
method
m.print();
} //end of main method
} //end of class
Volatile Modifier
 This modifier is applied only to private or object type
instance field or variable. Reserved keyword for this
modifier is volatile.
 It indicates to the JVM to merge a thread’s own copy
of field with the master copy of field available in
memory. When we access a volatile variable, it
synchronizes all the available cached copies of
variables in memory.
90
Volatile Modifier
public class Salary implements Runnable {
private volatile int salary;
public void run() {
salary = 5000; //assigning value to salary
do{
//loop body
}
while (salary <= 5000); // while loop definition
}
public void stop() {
salary = 5001; // new value assignment to salary
}
}
91
Transient Modifier
 When we use a transient modifier in an instance
variable declaration, the JVM will skip this
variable or field while serializing the object
containing that variable. Reserved keyword
is transient.
92
Transient Modifier
public abstract class Car{
//instance variable with transient modifier
public transient int number = 22114;
}
93
Synchronized Modifier
 A modifier that is used to restrict a method to be
used by any other thread when it is under use of
one thread. Reserved keyword for this modifier
is synchronized.
 The synchronized modifier can be used with any
access modifier.
94
Synchronized Modifier
public abstract class Car{
public synchronized make(){
//method body
}
}
95
Abstract Classes and Methods
 Data abstraction is the process of hiding certain
details and showing only essential information to
the user.
 Abstraction can be achieved with either abstract
classes or interfaces (which you will learn more
about in the next chapter).
96
Abstract Classes and Methods
 The abstract keyword is a non-access modifier, used
for classes and methods:
 Abstract class: is a restricted class that cannot be
used to create objects (to access it, it must be
inherited from another class).

Abstract method: can only be used in an abstract
class, and it does not have a body. The body is
provided by the subclass (inherited from).
97
Abstract Classes
 An abstract class can have both abstract and
regular methods:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
98
Abstract Classes
 From the example above, it is not possible to
create an object of the Animal class:
Animal myObj = new Animal(); // will generate an
error
 To access the abstract class, it must be inherited
from another class
99
Abstract Classes
// Abstract class
abstract class Animal {
// Abstract method (does not have a
body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is
provided here
System.out.println("The pig says:
wee wee");
}
}
100
class MyMainClass {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig
object
myPig.animalSound();
myPig.sleep();
}
}
JAVA 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.
101
JAVA Packages
Advantage of Java Package
1) Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
102
Java Packages
103
Java Packages Categories
 Built-in Packages (packages from the Java API)
 User-defined Packages (create your own
packages)
104
Built-in Packages
 The Java API is a library of prewritten classes, that
are free to use, included in the Java D
 To use a class or a package from the library, you
need to use the import keyword:evelopment
Environment.
Syntax
 import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
105
Built-in Packages
 If you find a class you want to use, for example,
the Scanner class, which is used to get user
input, write the following code:
Example
 import java.util.Scanner;
106
Example
import java.util.Scanner;
class MyClass
{ public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
String userName = myObj.nextLine();
System.out.println("Username is: " + userName);
}
}
107
Import a Package
 To import a whole package, end the sentence
with an asterisk sign (*). The following example
will import ALL the classes in
the java.util package:
Example
import java.util.*;
108
User-defined Packages
 To create your own package, you need to
understand that Java uses a file system
directory to store them. Just like folders on your
computer:
 Example
└── root
└── mypack
└── MyPackageClass.java
109
MyPackageClass.java
 To create a package, use the package keyword:
package mypack;
class MyPackageClass
{ public static void main(String[] args)
{ System.out.println("This is my package!"); } }
110
Java Packages
 Save the file as MyPackageClass.java, and
compile it:
 C:UsersYour Name>javac MyPackageClass.java
 compile the package:
 C:UsersYour Name>javac -d .
MyPackageClass.java
111
Java Packages
To run the MyPackageClass.java file, write the
following:
C:UsersYour Name>java
mypack.MyPackageClass
The output will be:
This is my package!
112
Java Packages
 Simple example of java package
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
113

More Related Content

PPT
PPT
Class and Object.ppt
PPT
Lect 1-class and object
PPT
Object & classes
PPTX
Inheritance & interface ppt Inheritance
PPT
Java sem i
PPT
Lecture 2 classes i
ODP
Ppt of c++ vs c#
Class and Object.ppt
Lect 1-class and object
Object & classes
Inheritance & interface ppt Inheritance
Java sem i
Lecture 2 classes i
Ppt of c++ vs c#

Similar to inheritance of java...basics of java in ppt (20)

PPT
PPT
Unit 1 Part - 3 constructor Overloading Static.ppt
PPTX
Class and Object.pptx
PDF
PPT
PPTX
C++ classes
PPT
Chapter 5 (OOP Principles).ppt
PPT
M251_Meeting 5 (Inheritance and Polymorphism).ppt
PPT
Oops concept in c#
PPT
packages and interfaces
PPTX
Oop objects_classes
PPT
Java Basics
PPTX
10. inheritance
PDF
Class and object in C++ By Pawan Thakur
PPTX
OBJECT ORIENTED PROGRAMING IN C++
PPTX
Classes and objects
PPTX
Classes and objects
PPTX
CORE JAVA PPT FOR ENGINEERS BBBBBBBBBBBBBBBBBBB
PPT
java02.pptsatrrhfhf https://www.slideshare.net/slideshow/java-notespdf-259708...
PPTX
Opp concept in c++
Unit 1 Part - 3 constructor Overloading Static.ppt
Class and Object.pptx
C++ classes
Chapter 5 (OOP Principles).ppt
M251_Meeting 5 (Inheritance and Polymorphism).ppt
Oops concept in c#
packages and interfaces
Oop objects_classes
Java Basics
10. inheritance
Class and object in C++ By Pawan Thakur
OBJECT ORIENTED PROGRAMING IN C++
Classes and objects
Classes and objects
CORE JAVA PPT FOR ENGINEERS BBBBBBBBBBBBBBBBBBB
java02.pptsatrrhfhf https://www.slideshare.net/slideshow/java-notespdf-259708...
Opp concept in c++
Ad

More from ssuserec53e73 (9)

PPTX
Query Processing in Database mgmt system
PPTX
Health care Analytics-Module 3-CADX150..
PPTX
Health care Analytics-Module 1-CADX150..
PPTX
Computer Forensics and investigation module 3
PPTX
Module 3 continuation of computer forensic
PPT
data acquisition in computer forensics and
PDF
DLF-Microprocessor_02_2017-18 SAE2B microprocessor
PPTX
Computer Forensics -Introduction and the details
PPT
COMPUTER FORENSICS MODULE III of unit 3.ppt
Query Processing in Database mgmt system
Health care Analytics-Module 3-CADX150..
Health care Analytics-Module 1-CADX150..
Computer Forensics and investigation module 3
Module 3 continuation of computer forensic
data acquisition in computer forensics and
DLF-Microprocessor_02_2017-18 SAE2B microprocessor
Computer Forensics -Introduction and the details
COMPUTER FORENSICS MODULE III of unit 3.ppt
Ad

Recently uploaded (20)

PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PDF
Open folder Downloads.pdf yes yes ges yes
PDF
English Language Teaching from Post-.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
From loneliness to social connection charting
PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PDF
Landforms and landscapes data surprise preview
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
How to Manage Loyalty Points in Odoo 18 Sales
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
PDF
Types of Literary Text: Poetry and Prose
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Sunset Boulevard Student Revision Booklet
PPTX
IMMUNIZATION PROGRAMME pptx
Revamp in MTO Odoo 18 Inventory - Odoo Slides
Open folder Downloads.pdf yes yes ges yes
English Language Teaching from Post-.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
From loneliness to social connection charting
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
Open Quiz Monsoon Mind Game Final Set.pptx
Landforms and landscapes data surprise preview
O7-L3 Supply Chain Operations - ICLT Program
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
Renaissance Architecture: A Journey from Faith to Humanism
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
How to Manage Loyalty Points in Odoo 18 Sales
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
Types of Literary Text: Poetry and Prose
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Sunset Boulevard Student Revision Booklet
IMMUNIZATION PROGRAMME pptx

inheritance of java...basics of java in ppt

  • 1. Classes and Objects in Java and Inheritance in Java 1 Basics of Classes in Java Recap
  • 2. Contents  Introduction to classes and objects in Java.  Understand how some of the OO concepts learnt so far are supported in Java.  Understand important feature inheritance in Java classes. 2
  • 3. Introduction  Java is a true OO language and therefore the underlying structure of all Java programs is classes.  Anything we wish to represent in Java must be encapsulated in a class that defines the “state” and “behavior” of the basic program components known as objects.  Classes create objects and objects use methods to communicate between them. They provide a convenient method for packaging a group of logically related data items and functions that work on them.  A class essentially serves as a template for an object and behaves like a basic data type “int”. It is therefore important to understand how the fields and methods are defined in a class and how they are used to build a Java program that incorporates the basic OO concepts such as encapsulation, inheritance, and polymorphism. 3
  • 4. Classes  A class is a collection of fields (data) and methods (procedure or function) that operate on that data. 4 Circle centre radius circumference() area()
  • 5. Classes  A class is a collection of fields (data) and methods (procedure or function) that operate on that data.  The basic syntax for a class definition:  Bare bone class – no fields, no methods 5 public class Circle { // my circle class } class ClassName { [fields declaration] [methods declaration] }
  • 6. Adding Fields: Class Circle with fields  Add fields  The fields (data) are also called the instance varaibles. 6 public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle }
  • 7. Adding Methods  A class with only data fields has no life. Objects created by such a class cannot respond to any messages.  Methods are declared inside the body of the class but immediately after the declaration of data fields.  The general form of a method declaration is: 7 type MethodName (parameter-list) { Method-body; }
  • 8. 8 public class Circle { public double x, y; // centre of the circle public double r; // radius of circle r = 2; //Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; } } Method Body
  • 9. Data Abstraction Can define variables (objects) of that type: Circle aCircle; Circle bCircle; Circle aCircle = new aCircle(); Circle bCircle=new bCircle(): 9 Data abstraction is the reduction of a particular body of data to a simplified representation of the whole
  • 10. Class of Circle cont.  aCircle, bCircle simply refers to a Circle object, not an object itself. 10 aCircle Points to nothing (Null Reference) bCircle Points to nothing (Null Reference) null null
  • 11. 11 Creating objects of a class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle;
  • 12. Creating objects of a class  Objects are created dynamically using the new keyword.  aCircle and bCircle refer to Circle objects  Circle aCircle; 12 bCircle = new Circle() ; aCircle = new Circle() ;
  • 13. 13 Creating objects of a class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; P aCircle Q bCircle Before Assignment P aCircle Q bCircle Before Assignment
  • 14. Automatic garbage collection  The object does not have a reference and cannot be used in future.  The object becomes a candidate for automatic garbage collection.  Java automatically collects garbage periodically and releases the memory used to be used in the future. 14
  • 15. Accessing Object/Circle Data  Similar to C syntax for accessing data defined in a structure. 15 Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0 ObjectName.VariableName ObjectName.MethodName(parameter-list)
  • 16. Executing Methods in Object/Circle  Using Object Methods: 16 Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area(); sent ‘message’ to aCircle
  • 17. Using Circle Class // Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) { Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area); System.out.println("Radius="+aCircle.r+" Circumference ="+circumf); } } 17 java MyMain Radius=5.0 Area=78.5 Radius=5.0 Circumference =31.400000000000002 public class Circle { public double x, y; // centre of the circle public double r; // radius of circle //Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; } }
  • 18. Inheritance in Java  It is the mechanism in java by which one class is allow to inherit the features(fields and methods) of another class. class ClassName [extends SuperClassName] { [fields declaration] [methods declaration] } 18
  • 19. Important terminology:  Super Class: The class whose features are inherited is known as super class(or a base class or a parent class).  Sub Class: The class that inherits the other class is known as sub class(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.  Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. 19
  • 21.  The keyword used for inheritance is extends. Syntax :  class derived-class extends base-class { //methods and fields } 21
  • 22. Types of Inheritance in Java  Single Inheritance : In single inheritance, subclasses inherit the features of one superclass. In image below, the class A serves as a base class for the derived class B. 22
  • 23. Example //Java program to illustrate the // concept of single inheritance import java.util.*; import java.lang.*; import java.io.*; class one { public void print_geek() { System.out.println("Geeks"); } } class two extends one { public void print_for() { System.out.println("for"); } } // Driver class public class Main { public static void main(String[] args) { two g = new two(); g.print_geek(); g.print_for(); g.print_geek(); } } 23
  • 24. Multilevel Inheritance  In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In below image, the class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members. 24
  • 26. Example for multilevel Inheritance import java.util.*; import java.lang.*; import java.io.*; class one { public void print_geek() { System.out.println("Geeks"); } } class two extends one { public void print_for() { System.out.println("for"); } } class three extends two { public void print_geek() { System.out.println("Geeks"); } } // Drived class public class Main { public static void main(String[] args) { three g = new three(); g.print_geek(); g.print_for(); g.print_geek(); } } 26
  • 27. Hierarchical Inheritance :  In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub class.In below image, the class A serves as a base class for the derived class B,C and D. 27
  • 28. // Java program to illustrate the // concept of Hierarchical inheritance import java.util.*; import java.lang.*; import java.io.*; class one { public void print_geek() { System.out.println("Geeks"); } } class two extends one { public void print_for() { System.out.println("for"); } } class three extends one { /*............*/ } // Drived class public class Main { public static void main(String[] args) { three g = new three(); g.print_geek(); two t = new two(); t.print_for(); g.print_geek(); } } 28
  • 29. Multiple Inheritance (Through Interfaces)  In Multiple inheritance ,one class can have more than one superclass and inherit features from all parent classes. Please note that Java does not support multiple inheritance with classes. In java, we can achieve multiple inheritance only through Interfaces. In image below, Class C is derived from interface A and B. 29
  • 31. Example of Multiple Inheritance // Java program to illustrate the // concept of Multiple inheritance import java.util.*; import java.lang.*; import java.io.*; interface one { public void print_geek(); } interface two { public void print_for(); } interface three extends one,two { public void print_geek(); } class child implements three { @Override public void print_geek() { System.out.println("Geeks"); } public void print_for() { System.out.println("for"); } } // Drived class public class Main { public static void main(String[] args) { child c = new child(); c.print_geek(); c.print_for(); c.print_geek(); } } 31
  • 32. Hybrid Inheritance(Through Interfaces)  It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces. 32
  • 34. Advantages of Inheritance  Reusability -- facility to use public methods of base class without rewriting the same  Extensibility -- extending the base class logic as per business logic of the derived class  Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived class  Overriding -- With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class. 34
  • 35. Method Overloading  If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.  It is also known as Compile-Time Polymorphism 35
  • 36. Overloading  If we have to perform only one operation, having same name of the methods increases the readability of the program 36
  • 37. Overloading  Different ways to overload the method There are two ways to overload the method in java  By changing number of arguments  By changing the data type 37
  • 38. Overloading  1) Method Overloading: changing no. of arguments class Adder{ static int add(int a,int b){return a+b;} static int add(int a,int b,int c){return a+b+c;} } class TestOverloading1{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); }} 38
  • 39. Overloading  2) Method Overloading: changing data type of arguments class Adder{ int add(int a, int b){return a+b;} double add(double a, double b){return a+b;} } class TestOverloading2{ public static void main(String[] args){ Adder ob1= new Adder(); Ob1.add(11,11); Ob1.add(11,12.6); //System.out.println(Adder.add(11,11)); //System.out.println(Adder.add(12.3,12.6)); }} 39
  • 40. Method Overriding  If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.  In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding. 40
  • 41. Overriding  Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. 41
  • 42. Overriding  When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. 42
  • 44. Usage of Java Method Overriding  Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.  Method overriding is used for runtime polymorphism 44
  • 45.  Rules for Java Method Overriding  The method must have the same name as in the parent class  The method must have the same parameter as in the parent class.  There must be an IS-A relationship (inheritance). 45
  • 46. Overriding class Vehicle{ //defining a method void run(){System.out.println("Vehicle is running");} } //Creating a child class class Bike2 extends Vehicle{ //defining the same method as in the parent class void run(){System.out.println("Bike is running safely");} public static void main(String args[]){ Bike2 obj = new Bike2();//creating object obj.run();//calling method } } Output: Bike is running safely 46
  • 47. Scope of the Variable Method Scope Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared. 47
  • 48. Scope of Variables in Java  Scope is that area of the program where the variable is visible to a program and can be used (accessible).  i.e. the scope of variable determines its accessibility for other parts of program.  Java allows declaring variables within any block. A block defines scope that starts with an opening curly brace and ends with a closing curly brace.  There are three types of variables in java, depending on their scope: local variables, instance variables, and class variables (static variables). 48
  • 49. Scope of Variables in Java  1. Scope of Local Variables in Java  2. Scope of Instance variables in Java  3. Scope of Static variables 49
  • 50. Scope of the method public class MyClass { public static void main(String[] args) { // Code here cannot use x int x = 100; // Code here can use x System.out.println(x); } } 50
  • 51. Block Scope  A block of code refers to all of the code between curly braces {}  Variables declared inside blocks of code are only accessible by the code between the curly braces which follows the line in which the variable was declared.  A block of code may exist on its own or it may belong to an if, while or for statement. In the case of for statements, variables declared in the statement itself are also available inside the block's scope. 51
  • 52. Example Program public class MyClass { public static void main(String[] args) { // Code here CANNOT use x { // This is a block // Code here CANNOT use x int x = 100; // Code here CAN use x System.out.println(x); } // The block ends here // Code here CANNOT use x } } 52
  • 53. Java Modifiers Modifiers divided into two groups: Access Modifiers - controls the access level Non-Access Modifiers - do not control access level, but provides other functionality 53
  • 54. The four primary access modifiers in Java are:  Default access modifier  Protected access modifier  Public access modifier  Private access modifier 54
  • 55. Access Modifiers For classes, we can use either public or default public :The class is accessible by any other class default :The class is only accessible by classes in the same package. This is used when you don't specify a modifier. //You will learn more about packages in the Packages chapter 55
  • 56. Access Modifiers For attributes, methods and constructors, you can use one of the following: public :The code is accessible for all classes private :The code is only accessible within the declared class default :The code is only accessible in the same package. This is used when you don't specify a modifier. You will learn more about packages in the Packages chapter protected :The code is accessible in the same package and subclasses. You will learn more about subclasses and superclasses in the Inheritance chapter 56
  • 57. Non-Access Modifiers For classes, we can use either final or abstract: final:The class cannot be inherited by other classes abstract :The class cannot be used to create objects (To access an abstract class, it must be inherited from another class. You will learn more about inheritance and abstraction in the Inheritance and Abstraction chapters) 57
  • 58. Non Access Modifiers final Attributes and methods cannot be overridden/modified static Attributes and methods belongs to the class, rather than an object abstract Can only be used in an abstract class, and can only be used on methods. The method does not have a body, for example abstract void run();. The body is provided by the subclass (inherited from). You will learn more about inheritance and abstraction in the Inheritance and Abstraction chapters transient Attributes and methods are skipped when serializing the object containing them synchronize d Methods can only be accessed by one thread at a time volatile The value of an attribute is not cached thread-locally, and is always read from the "main memory" 58
  • 61. Java Package  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. 61
  • 62. Java Packages  There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Advantage of Java Package  Java package is used to categorize the classes and interfaces so that they can be easily maintained.  Java package provides access protection.  Java package removes naming collision. 62
  • 64. Syntax to create packages package nameOfPackage; 64
  • 65. Java Packages Consider the following package program in Java: package pack; public class A { public void msg() {System.out.println("Hello"); } } 65
  • 66. Java Packages package mypack; import pack.*; class B{ public static void main(String args[]) { A obj = new A(); obj.msg(); } } 67
  • 68. 69
  • 69. Default access modifiers  The default access modifier is accessible to any package by default. The programmers need not specify any keyword to use the default access modifier.  It means that the programmer doesn’t need to specify a class, method, or constructor default explicitly.  A class or method is, by default, accessible from any other “class” that exists in the same package. We usually don’t define variables and methods with any access modifier. 70
  • 70. Example Code class Def { int num = 175; void print() { System.out.println("Default class " + num); } } public class Test { public static void main(String args[]) { Def def = new Def(); def.print(); } } Output: Default class 175 71
  • 71. Private access modifiers  As the name suggests, the private access modifier limits access to the defining “class” only. With the help of the “private” keyword, we can implement the real concept of Data Encapsulation. It means to hide the private members form the outside world.  The functions labeled as private are accessible within the class only.  You can’t declare a top-level class or interface as private. Also, if so, then it would be useless as no one could access it.  The programmer must define a getter or setter to access private methods or variables. 72
  • 72. The example below will help you visualize a getter for the private method: class Priv { private void PRINT() { System.out.println("Private access"); } public void getPrint() { PRINT(); } } public class Test { public static void main(String args[]) { Private priv = new Priv(); priv.PRINT(); } } Output:Private access 73
  • 73. Public access modifiers  The public modifiers are the most common in Java applications. They mean that any public class, method, variable, interface, or constructor is accessible throughout the package.  Before using a public class in another package, you must first import it.  If you inherit a public class, then the subclass will have all its methods and variables by default. 74
  • 74. Example Code For Public access modifier public class First { public void print() { System.out.println("Hello"); } public class Test extends First { public static void main(String args[]) { First first = new First(); first.print(); } } Output:Hello 75
  • 75. Protected access modifiers  Objects or methods having protected access are visible to the package and subclasses only.  The following are a few points to elaborate on the exact behavior:  These methods, variables, or constructors are accessible within the package only and also available to all the subclasses.  The protected keyword doesn’t apply to any class or interface.  Interface methods or variables can’t have protected access. 76
  • 76. Example Code for Protected Access: public class First { protected static int count; public void update(){ System.out.println(++count); } public class Test extends First { public static void main(String args[]) { First out = new First(); out.update(); } } }Output:1 77
  • 77. Non-access modifiers  Static – It means something is directly related to a class.  Final – It indicates that the object is immutable.  Abstract – It means you need to subclass for creating objects.  Synchronized – It indicates that only one thread can execute a method at a time.  Transient – It means to exclude something during serialization.  Volatile – It indicates that different threads can modify a variable’s value.  Native – It shows that the method is available in the native code using JNI or JNA. 78
  • 78. Static Modifier  Static Modifier is used for creating a static variable and static method.  The reserved keyword for a static modifier is static, which is used before the data type of the variable or method.  A static method or variable exists independently of any class object.  It means a static variable or static method can be called using the class name without creating an instance or object of this class. 79
  • 79. Static Modifier  Car.java public class Car{ public static String msg; //String type static variable is declared public static void create(){ System.out.print(msg); //Variable msg is passed as argument to print. } } 80
  • 80. Static Modifier Main.java public class Main { //initialization of class public static void main(String[] args) { //value is stored in static variable Car.msg = "A new car has been created"; // static method in class Car is invoked Car.create(); } } 81
  • 81. Final Modifier  In Java, variable, method, and class can have a final non-access modifier. The reserved keyword for a final non-access modifier is final. This keyword is used to make any class, method, or variable final.  Once a final variable is initialized, you cannot change its value again. A final variable that is uninitialized is called a blankfinal variable that can be initialized only in the constructor of a class. To make a class variable, sometimes, we use the static keyword with final. If a static final variable is not initialized, we can initialize it in a static block. 82
  • 82. Final Modifier public class Main{ //initialization of class //declare a final variable of int data type public final int number = 1; //non-static method to print number value public void print(){ System.out.print(number); //print number number = 2; //change value of number System.out.print(number); //print new value } // main method public static void main(String[] args){ //object of class Main to access non-static methods Main p = new Main(); //print method invoked p.print(); } } //end of class 83
  • 83. If we remove code at line 11, the modified code would be executed without any error. Code Example for Final Variable: public class Main{ //initialization of class //declare a final variable of int data type public final int number = 1; //non-static method to print number value public void print(){ System.out.print("Output is "+number); //print number } // main method public static void main(String[] args){ //object of class Main to access non-static methods Main p = new Main(); //print method invoked p.print(); } } //end of class 84
  • 84.  Code Example for Static Final Variable: public class Main{ //initialization of class //declare a static final variable of int data type public static final int number = 1; // main method public static void main(String[] args){ System.out.print("Output is "+number); //print number } } //end of class  A method that we cannot override is called final method. It can be inherited in any other class. 85
  • 85. Code Example for Final Method: Car.java public class Car{ //final method public final void create(){ System.out.print("I'm final method to create a car."); } } Main.java //initialization of class public class Main extends Car{ //non-static method to access non-static methods in Car.java public void makeCar(){ create(); //method invoked } // main method public static void main(String[] args){ Main m = new Main(); //object of Main class m.makeCar(); //call to makeCar method } //end of main method } //end of class 86
  • 86. A class that we cannot extend is called final class. It means a final class cannot be inherited by any other class.  Code Example for Final Class: Car.java public final class Car{ //void method public void print(){ //method body } } Main.java //initialization of class public class Main extends Car{ public static void main(String[] args){ } //end of main method } //end of class 87
  • 87. Abstract Modifier  A class or method can be declared as abstract. Reserved keyword abstract is used for the abstract modifier.  An abstract class or method cannot be final because an abstract class is made with the purpose of extending it in other classes and an abstract method is made for the sole purpose of overriding the method body. To make a class abstract, at least one abstract method should be defined in a class. If we have to declare abstract methods in a class, a class must be an abstract class.  An abstract method is just a declaration; it does not contain an implementation or method body. You will have to define its implementation by overriding this method in a class, which has extended the abstract class. When a class extends an abstract class, all the abstract methods defined in the abstract class must be overridden in a subclass. 88
  • 88. Example Code: Abstact Modifier Car.java public abstract class Car{ public abstract void create(); public void print(){ System.out.print("I'm not abstract method."); } } 89 Main.java //initialization of class public class Main extends Car{ // overriding method defined in Car class //as create is only abstract method in Car class //overriding it is compulsory //otherwise error will occur @Override public void create(){ System.out.println("I'm overridden method."); } // main method public static void main(String[] args){ Main m = new Main(); //object of Main class m.create(); //invoking overridden method m.print(); } //end of main method } //end of class
  • 89. Volatile Modifier  This modifier is applied only to private or object type instance field or variable. Reserved keyword for this modifier is volatile.  It indicates to the JVM to merge a thread’s own copy of field with the master copy of field available in memory. When we access a volatile variable, it synchronizes all the available cached copies of variables in memory. 90
  • 90. Volatile Modifier public class Salary implements Runnable { private volatile int salary; public void run() { salary = 5000; //assigning value to salary do{ //loop body } while (salary <= 5000); // while loop definition } public void stop() { salary = 5001; // new value assignment to salary } } 91
  • 91. Transient Modifier  When we use a transient modifier in an instance variable declaration, the JVM will skip this variable or field while serializing the object containing that variable. Reserved keyword is transient. 92
  • 92. Transient Modifier public abstract class Car{ //instance variable with transient modifier public transient int number = 22114; } 93
  • 93. Synchronized Modifier  A modifier that is used to restrict a method to be used by any other thread when it is under use of one thread. Reserved keyword for this modifier is synchronized.  The synchronized modifier can be used with any access modifier. 94
  • 94. Synchronized Modifier public abstract class Car{ public synchronized make(){ //method body } } 95
  • 95. Abstract Classes and Methods  Data abstraction is the process of hiding certain details and showing only essential information to the user.  Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the next chapter). 96
  • 96. Abstract Classes and Methods  The abstract keyword is a non-access modifier, used for classes and methods:  Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).  Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from). 97
  • 97. Abstract Classes  An abstract class can have both abstract and regular methods: abstract class Animal { public abstract void animalSound(); public void sleep() { System.out.println("Zzz"); } } 98
  • 98. Abstract Classes  From the example above, it is not possible to create an object of the Animal class: Animal myObj = new Animal(); // will generate an error  To access the abstract class, it must be inherited from another class 99
  • 99. Abstract Classes // Abstract class abstract class Animal { // Abstract method (does not have a body) public abstract void animalSound(); // Regular method public void sleep() { System.out.println("Zzz"); } } // Subclass (inherit from Animal) class Pig extends Animal { public void animalSound() { // The body of animalSound() is provided here System.out.println("The pig says: wee wee"); } } 100 class MyMainClass { public static void main(String[] args) { Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); } }
  • 100. JAVA 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. 101
  • 101. JAVA Packages Advantage of Java Package 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision. 102
  • 103. Java Packages Categories  Built-in Packages (packages from the Java API)  User-defined Packages (create your own packages) 104
  • 104. Built-in Packages  The Java API is a library of prewritten classes, that are free to use, included in the Java D  To use a class or a package from the library, you need to use the import keyword:evelopment Environment. Syntax  import package.name.Class; // Import a single class import package.name.*; // Import the whole package 105
  • 105. Built-in Packages  If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code: Example  import java.util.Scanner; 106
  • 106. Example import java.util.Scanner; class MyClass { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); System.out.println("Enter username"); String userName = myObj.nextLine(); System.out.println("Username is: " + userName); } } 107
  • 107. Import a Package  To import a whole package, end the sentence with an asterisk sign (*). The following example will import ALL the classes in the java.util package: Example import java.util.*; 108
  • 108. User-defined Packages  To create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer:  Example └── root └── mypack └── MyPackageClass.java 109
  • 109. MyPackageClass.java  To create a package, use the package keyword: package mypack; class MyPackageClass { public static void main(String[] args) { System.out.println("This is my package!"); } } 110
  • 110. Java Packages  Save the file as MyPackageClass.java, and compile it:  C:UsersYour Name>javac MyPackageClass.java  compile the package:  C:UsersYour Name>javac -d . MyPackageClass.java 111
  • 111. Java Packages To run the MyPackageClass.java file, write the following: C:UsersYour Name>java mypack.MyPackageClass The output will be: This is my package! 112
  • 112. Java Packages  Simple example of java package //save as Simple.java package mypack; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } } 113