SlideShare a Scribd company logo
UNIT 3: CLASSES,
INHERITANCE, PACKAGES
AND INTERFACES
CONTENTS
• Object-Oriented Concepts
• Inheritance
• Package
• Interfaces
2
1. OBJECT-ORIENTED CONCEPTS
o Classes – Class fundamentals
o Methods, naming conventions
o Declaring objects
o Access specifiers
o Constructors – Introduction
o Command line arguments
o Constructor overloading
3
CLASS
A class in Java is a set of objects which shares common characteristics/ behavior
and common properties/ attributes. It is a user-defined blueprint or prototype
from which objects are created. It is a logical entity. It can't be physical.
For example, student is a class while a particular student named Ann is an
object.
Properties of Java Classes:
• Class is not a real-world entity. It is just a template or blueprint or prototype
from which objects are created.
• Class does not occupy memory.
• Class is a group of variables of different data types and a group of methods.
• A Class in Java can contain:
 Data member/ fields
 Methods
 Constructors
 Nested Class
 Interface
Syntax to declare a class:
class <class_name>
{
field; method;
}
class Student
{
int id; String name;
}
class TestStudent1
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
OBJECT
An entity that has state and behavior is known as an object e.g., a chair, bike,
marker, pen, table, car, etc. It can be physical or logical. An object is an instance of
a class.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its
state. It is used to write, so writing is its behavior.
OBJECT
Syntax for creating an object:
ClassName objectName = new ClassName(arguments);
Initializing an object:
There are 3 ways to initialize an object in Java.
1. By reference variable
2. By method
3. By constructor
1. Initialize the object through a reference variable.
2. Initialization through method.
3. Initialization through Constructors.
public class Person {
String name;
int age;
// Constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
public static void main(String[] args) {
// Initialize using the constructor
Person p = new Person("Alice", 30);
System.out.println(p.name); // Outputs: Alice
System.out.println(p.age); // Outputs: 30
}
}
Class
• It should start with the uppercase letter.
• It should be a noun such as Color, Button, System, Thread, etc.
• Use appropriate words, instead of acronyms.
Example: - public class Employee { //code snippet }
JAVA NAMING CONVENTIONS
Method
• It should start with lowercase letter.
• It should be a verb such as main(), print(), println().
• If the name contains multiple words, start it with a lowercase letter followed by an uppercase
letter such as actionPerformed().
Example:-
class Employee
{
//method
void draw()
{
//code snippet
}
}
JAVA NAMING CONVENTIONS
Variable
• It should start with a lowercase letter such as id, name.
• It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore).
• If the name contains multiple words, start it with the lowercase letter followed by an uppercase
letter such as firstName, lastName.
• Avoid using one-character variables such as x, y, z.
Example :-
class Employee
{
//variable
int id;
//code snippet
}
JAVA NAMING CONVENTIONS
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
ACCESS SPECIFIER
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default. No keyword required.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
ACCESS SPECIFIER
1. Default Access Modifier
Compile time error
What is the output?
2. Private Access Modifier
What is the output?
3. Protected Access Modifier
What is the output?
4. Public Access modifier
What is the output?
UNIT 3- Java- Inheritance, Multithreading.pptx
The method in Java or Methods of Java is a collection of statements that perform some
specific tasks and return the result to the caller. A Java method can perform some
specific tasks without returning anything. Java Methods allows us to reuse the code
without retyping the code. In Java, every method must be part of some class that is
different from languages like C, C++, and Python.
<access_modifier> <return_type>
<method_name>( list_of_parameters)
{
//body
}
JAVA METHODS
UNIT 3- Java- Inheritance, Multithreading.pptx
UNIT 3- Java- Inheritance, Multithreading.pptx
A constructor is a special method in a class that is called when an object of that class is
created. The primary purpose of a constructor is to initialize the newly created object.
• A constructor in Java is a special method that is used to initialize objects.
• The constructor is called when an object of a class is created.
• Every time an object is created using the new() keyword, at least one constructor is
called.
JAVA CONSTRUCTORS
Object Creation and Constructor Invocation
When you use the new keyword to create an object, Java performs
several steps:
• Memory Allocation: Java allocates memory for the new object.
• Constructor Invocation: Java calls a constructor to initialize the
newly created object. This is where the object's fields are set up
and any initialization logic defined in the constructor is executed.
• Initialization: The constructor initializes the object's fields with the
provided arguments or default values.
JAVA CONSTRUCTORS
Output  5
Rules for creating Java constructor
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and
synchronized
JAVA CONSTRUCTORS
Types of Java constructors
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_name>()
{
//code snippet
}
JAVA CONSTRUCTORS
Java Default Constructor
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
JAVA CONSTRUCTORS
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a
parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to
distinct objects. However, you can provide the same values also. Example
of parameterized constructor In this example, we have created the
constructor of Student class that have two parameters. We can have any
number of parameters in the constructor.
JAVA CONSTRUCTORS
UNIT 3- Java- Inheritance, Multithreading.pptx
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type.
It can also be overloaded like Java methods. Constructor overloading in
Java is a technique of having more than one constructor with different
parameter lists.
They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters
in the list and their types.
JAVA CONSTRUCTORS
class Student5
{
int id; String name; int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i,String n,int a)
{
id = i; name = n; age=a;
}
JAVA CONSTRUCTORS
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Arun");
Student5 s2 = new Student5(222,"Bose",25);
s1.display();
s2.display();
}
}
Copy Constructor
There is no copy constructor in Java. However, we can copy the values from
one object to another like copy constructor in C++.
In this example, we are going to copy the values of one object into
another using Java constructor.
JAVA CONSTRUCTORS
Java Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of
running the java program.
The arguments passed from the console can be received in the java
program and it can be used as an input. So, it provides a convenient way to
check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.
JAVA CONSTRUCTORS
Example:
class A
{
public static void main(String
args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
NON – ACCESS SPECIFIERS IN JAVA
Static
Final
Abstract
Volatile
Synchronize
Transient etc.,
2. INHERITANCE
o Introduction
o Single-level inheritance
o Multilevel inheritance
o Method overriding
o Dynamic method dispatch
o Abstract classes
o Usage of super, final, this, and abstract keyword
39
40
WHY DO WE NEED JAVA INHERITANCE?
Code Reusability: The code written in the Superclass is common to
all subclasses. Child classes can directly use the parent class code.
Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
Abstraction: The concept of abstract where we do not have to
provide all details, is achieved through inheritance. Abstraction only
shows the functionality to the user.
JAVA INHERITANCE
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super
class. It inherits the properties and behavior of a single-parent
class. Sometimes, it is also known as simple inheritance. In the
below figure, ‘A’ is a parent class and ‘B’ is a child class. The class
‘B’ inherits all the properties of the class ‘A’.
class Single
{
static int num1=10;
static int num2=5;
}
class Inherit extends Single
{
public static void main(String[] args)
{
int num3=2;
int result=num1+num2+num3;
System.out.println("Result of child class is "+result);
}
}
JAVA INHERITANCE
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a
base class, and as well as the derived class also acts as the base
class for other classes. In the below image, 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.
Class X
{
public void methodX()
{
System.out.println("Class X
method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y
method");
} }
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX();
//calling grand parent class method
obj.methodY();
//calling parent class method
obj.methodZ();
//calling local method
} }
JAVA INHERITANCE
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass
(base class) for more than one subclass. In the below image,
class A serves as a base class for the derived classes B, C, and D.
UNIT 3- Java- Inheritance, Multithreading.pptx
UNIT 3- Java- Inheritance, Multithreading.pptx
JAVA INHERITANCE
4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances, one class can have more than one
superclass and inherit features from all parent classes. Java
does not support multiple inheritances with classes. In Java, we
can achieve multiple inheritances only through Interfaces. Class
C is derived from interfaces A and B.
JAVA INHERITANCE
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance.
Since Java doesn’t support multiple inheritances with classes,
hybrid inheritance involving multiple inheritance is also not
possible with classes. In Java, we can achieve hybrid inheritance
only through Interfaces if we want to involve multiple
inheritance to implement Hybrid inheritance.
METHOD OVERRIDING
If subclass (child class) has the same method as declared in the
parent class, it is known as Method Overriding.
class Vehicle
{
void run()
{System.out.println("Vehicle is running");
}
}
class Bike2 extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
obj.run();
}
METHOD OVERLOADING
If a class has multiple methods having same name but different
in parameters, it is known as Method Overloading. If we have to
perform only one operation, having same name of the methods
increases the readability of the program.
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
UNIT 3- Java- Inheritance, Multithreading.pptx
METHOD OVERLOADING VS METHOD OVERRIDING
DYNAMIC METHOD DISPATCH
•Dynamic method dispatch in Java is a mechanism that allows a Java
program to call methods on objects at runtime based on the
object's actual type, not the type of the reference used to call the
method. This is an example of polymorphism in action.
•Dynamic Method Dispatch allows the JVM to determine which
method implementation to call at runtime based on the actual
object type, not the type of the reference.
•It’s used to achieve runtime polymorphism
•.
How It Works
Base Class and Subclasses: You have a base class (superclass) and
one or more subclasses.
Method Overriding: The subclass overrides a method from the base
class.
Reference Variable: You use a base class reference to hold an object
of the subclass.
Method Call: When you call the method using the base class
reference, the JVM looks at the actual object type (subclass) and calls
the overridden method in that subclass.
UNIT 3- Java- Inheritance, Multithreading.pptx
UNIT 3- Java- Inheritance, Multithreading.pptx
ABSTRACT AND SUPER
Abstraction in Java
Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
For example
Sending SMS where you type the text and send the message. You don't
know the internal processing about the message delivery. Abstraction
lets you focus on what the object does instead of how it does it.
Abstract class in Java A class which is declared as abstract is known as
an abstract class.
It can have abstract and non-abstract methods. It needs to be
extended and its method implemented. It cannot be instantiated.
•.
ABSTRACT AND SUPER
Points to Remember
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body of the
method.
Example of abstract class
abstract class A
{
}
•.
Abstract Method in Java
A method which is declared as abstract and does not have implementation is
known as an abstract method.
Example of abstract method
abstract void printStatus(); //no method body and abstract
Example:
abstract class Animal
{
public abstract void sound();
}
public class Dog extends Animal
{
public void sound()
{
System.out.println(“Bark");
}
public static void main(String args[])
{
Animal obj = new Dog();
obj.sound();
}
}
ABSTRACT AND SUPER
SUPER
The super keyword is used in object-oriented programming
languages like Java and C++ to refer to the superclass (parent
class) of the current object. It can be used to access superclass
methods, constructors, and variables, especially when they are
overridden or hidden by the subclass (child class).
UNIT 3- Java- Inheritance, Multithreading.pptx
UNIT 3- Java- Inheritance, Multithreading.pptx
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance
variable.
2. super can be used to invoke immediate parent class
method.
3. super() can be used to invoke immediate parent class
constructor.
super is used to refer immediate parent class instance
variable.
super can be used to invoke parent class method.
super is used to invoke parent class constructor
FINAL AND THIS
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized
final variable. It can be initialized in the constructor only. The blank
final variable can be static also which will be initialized in the static
block only.
•.
FINAL AND THIS
1) Java final variable - If you make any variable as final, you cannot
change the value of final variable(It will be constant).
•.
UNIT 3- Java- Inheritance, Multithreading.pptx
FINAL AND THIS
2) Java final method
If you make any method as final, you cannot override it.
•.
UNIT 3- Java- Inheritance, Multithreading.pptx
FINAL AND THIS
3) Java final class -
If you make any class as final, you cannot extend it.
•.
UNIT 3- Java- Inheritance, Multithreading.pptx
this keyword
In java, this is a reference variable that refers to the
current object.
Usage of java this keyword
1. this can be used to refer current class instance
variable.
2. this can be used to invoke current class method
(implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method
call.
5. this can be passed as argument in the constructor
UNIT 3- Java- Inheritance, Multithreading.pptx
3. PACKAGE
o Define package
o Access protection/modifiers
o Importing packages
o Lang package – wrapper class
o File input stream and output stream
77
78
3. PACKAGE
In Java, a package is a namespace that organizes a set of
related classes and interfaces. Packages help avoid
naming conflicts and can control access to classes,
methods, and variables. They also provide a way to
group related code together, making it easier to manage
large codebases.
79
JAVA IN-BUILT PACKAGES/ JAVA API PACKAGES
• java.lang  Core classes  Fundamental classes such as
Object, String, Math, Thread, and System.
• java.io  Input and Output  classes for input and output
operations like File, InputStream, OutputStream, and Reader.
• java.util  Utility classes  Utility classes including
collections (ArrayList, HashMap), date and time utilities, and
more.
• java.applet  Applets  to implement applet programs
Package name  Purpose 
Description
80
• java.awt  AWT  Classes for GUI creation and
graphics, including Frame, Button, and Graphics.
• java.net  Networking  Classes for developing
network programs, including Socket, ServerSocket, URL,
and HttpURLConnection
• java.sql  Java Database Connectivity  Classes related
to database access
• javax.swing  Swings  These classes provide easy-to-
use and flexible components for building GUI. The
components in this package are referred to as Swing
components
Package name  Purpose 
Description
81
• Find out 5 important classes from each
package along with their description
82
IMPORTING BUILTIN PACKAGES
import java.util.*; //all classes(entire
package)
import java.util.Vector; //import Vector class
from util package
import.java.awt.*; //all the classes of awt will
be imported not the sub-package
import.java.awt.event.*; //imports the sub
package and all its classes
83
DEFINING USER DEFINED PACKAGES
Syntax
package packagename;
Example:
package pkg1;
84
STEPS FOR CREATING USER DEFINED PACKAGES
Step 1: Create a program which is a part of the defined package (here it
is pack1).
Step 2: Place your file (Greeting.java) in any drive/ folder path and compile
the program
85
Lets use a command and place the above in D drive
cd..  d:  D: > javavc –d . Greeting.java
The Pack1 directory will be created automatically by the
compiler.
Step 3: Create another file Greeting2.java in pack2
package
Step 4: you can import the defined package here.
86
87
JAVA WRAPPER CLASS
• In Java, wrapper classes are used to convert
primitive data types into objects.
• This is important because Java collections (like
ArrayList and HashMap) and some methods
require objects rather than primitive types.
• We use wrapper classes while working with
those data structures where primitive types
cannot be used.
88
• Each primitive data type has a corresponding wrapper class in the java.lang
package:
89
• Key Concepts
1.Autoboxing and Unboxing
Autoboxing is the automatic conversion of a primitive type to its
corresponding wrapper class when needed, and unboxing is the reverse process.
This conversion happens automatically, so you don't usually have to do it manually.
Autoboxing Example:
Integer integerObject = 5; // int 5 is automatically converted to Integer.
Unboxing Example:
int primitiveInt = integerObject; // Integer is automatically converted to int
90
class Unboxing
{
public static void main(String[] args)
{
Integer x = 10;
System.out.println(x);
int i = 20;
Integer y = new Integer(i);
System.out.println();
}
}
4. INTERFACES
o Defining an interface
o Implementing interfaces
o Variables in interfaces
o Extending interfaces
91
INTERFACES
An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract
methods. It is used to achieve abstraction and multiple inheritances in Java. In other words,
interfaces primarily define methods that other classes must implement. Traditionally, an interface
could only have abstract methods (methods without a body) and public, static, and final variables by
default.
In Java, the abstract keyword applies only to classes and methods, indicating that they cannot be
instantiated directly and must be implemented.
INTERFACES
Syntax for Java Interfaces
why use interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in the interface are
final, public, and static.
INTERFACES
Relationship Between Class and Interface
A class can extend another class, and similarly, an interface can extend another interface. However,
only a class can implement an interface, and the reverse (an interface implementing a class) is not
allowed.
INTERFACES
Difference Between Class and Interface
96
INTERFACES
Implementation: To implement an interface, we use the keyword
implements
97
98
INTERFACES
Multiple Inheritance in Java Using Interface
Multiple Inheritance is an OOPs concept that can’t be implemented in Java using classes.
100
101
Output  Implementation of methodA
Implementation of methodB
102
IMPORTANT POINTS IN JAVA INTERFACEST
POINTS IN JAVA INTERFACES
• We can’t create an instance (interface can’t be instantiated)
of the interface but we can make the reference of it that
refers to the Object of its implementing class.
• A class can implement more than one interface.
• An interface can extend to another interface or interface
(more than one interface).
• A class that implements the interface must implement all
the methods in the interface. All the methods are public
and abstract. All the fields are public, static, and final.
• It is used to achieve multiple inheritances.
103
• It is used to achieve loose coupling.
• Inside the Interface not possible to declare instance
variables because by default variables are public static
final.
• Inside the Interface, constructors are not allowed.
• Inside the interface main method is not allowed.
• Inside the interface, static, final, and private methods
declaration are not possible.
THANK YOU

More Related Content

Similar to UNIT 3- Java- Inheritance, Multithreading.pptx (20)

PPTX
Nitish Chaulagai Java1.pptx
NitishChaulagai
 
PPTX
Android Training (Java Review)
Khaled Anaqwa
 
PPT
Java_notes.ppt
tuyambazejeanclaude
 
PPTX
Java Programs
vvpadhu
 
PPT
Md03 - part3
Rakesh Madugula
 
PPTX
Jaga codinghshshshshehwuwiwijsjssnndnsjd
rajputtejaswa12
 
PPTX
Java Classes fact general wireless-19*5.pptx
IbrahimMerzayiee
 
PPTX
2- Introduction to java II
Ghadeer AlHasan
 
PDF
Java basic concept
University of Potsdam
 
PPTX
object oriented programming using java, second sem BCA,UoM
ambikavenkatesh2
 
PPTX
Classes, Inheritance ,Packages & Interfaces.pptx
DivyaKS18
 
PPTX
Presentation2.ppt java basic core ppt .
KeshavMotivation
 
PPT
Jacarashed-1746968053-300050282-Java.ppt
DilipDas70
 
PPT
JavaTutorials.ppt
Khizar40
 
PPT
Java
s4al_com
 
PDF
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
PPTX
Ch-2ppt.pptx
ssuser8347a1
 
PPTX
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
Indu65
 
PPTX
Class and Object.pptx from nit patna ece department
om2348023vats
 
Nitish Chaulagai Java1.pptx
NitishChaulagai
 
Android Training (Java Review)
Khaled Anaqwa
 
Java_notes.ppt
tuyambazejeanclaude
 
Java Programs
vvpadhu
 
Md03 - part3
Rakesh Madugula
 
Jaga codinghshshshshehwuwiwijsjssnndnsjd
rajputtejaswa12
 
Java Classes fact general wireless-19*5.pptx
IbrahimMerzayiee
 
2- Introduction to java II
Ghadeer AlHasan
 
Java basic concept
University of Potsdam
 
object oriented programming using java, second sem BCA,UoM
ambikavenkatesh2
 
Classes, Inheritance ,Packages & Interfaces.pptx
DivyaKS18
 
Presentation2.ppt java basic core ppt .
KeshavMotivation
 
Jacarashed-1746968053-300050282-Java.ppt
DilipDas70
 
JavaTutorials.ppt
Khizar40
 
Java
s4al_com
 
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
Ch-2ppt.pptx
ssuser8347a1
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
Indu65
 
Class and Object.pptx from nit patna ece department
om2348023vats
 

More from shilpar780389 (6)

PPTX
BCA - Chapter Groups- presentation(ppt).pptx
shilpar780389
 
PPTX
Internet_Technology_UNIT V- Introduction to XML.pptx
shilpar780389
 
PPTX
Data Structures-UNIT Four_Linked_List.pptx
shilpar780389
 
PPTX
UNIT – 2 Features of java- (Shilpa R).pptx
shilpar780389
 
PPTX
Unit 1 – Introduction to Java- (Shilpa R).pptx
shilpar780389
 
PPTX
Unit 2- Control Structures in C programming.pptx
shilpar780389
 
BCA - Chapter Groups- presentation(ppt).pptx
shilpar780389
 
Internet_Technology_UNIT V- Introduction to XML.pptx
shilpar780389
 
Data Structures-UNIT Four_Linked_List.pptx
shilpar780389
 
UNIT – 2 Features of java- (Shilpa R).pptx
shilpar780389
 
Unit 1 – Introduction to Java- (Shilpa R).pptx
shilpar780389
 
Unit 2- Control Structures in C programming.pptx
shilpar780389
 
Ad

Recently uploaded (20)

PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Advancing WebDriver BiDi support in WebKit
Igalia
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Advancing WebDriver BiDi support in WebKit
Igalia
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Biography of Daniel Podor.pdf
Daniel Podor
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
Ad

UNIT 3- Java- Inheritance, Multithreading.pptx

  • 1. UNIT 3: CLASSES, INHERITANCE, PACKAGES AND INTERFACES
  • 2. CONTENTS • Object-Oriented Concepts • Inheritance • Package • Interfaces 2
  • 3. 1. OBJECT-ORIENTED CONCEPTS o Classes – Class fundamentals o Methods, naming conventions o Declaring objects o Access specifiers o Constructors – Introduction o Command line arguments o Constructor overloading 3
  • 4. CLASS A class in Java is a set of objects which shares common characteristics/ behavior and common properties/ attributes. It is a user-defined blueprint or prototype from which objects are created. It is a logical entity. It can't be physical. For example, student is a class while a particular student named Ann is an object. Properties of Java Classes: • Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created. • Class does not occupy memory. • Class is a group of variables of different data types and a group of methods.
  • 5. • A Class in Java can contain:  Data member/ fields  Methods  Constructors  Nested Class  Interface Syntax to declare a class: class <class_name> { field; method; }
  • 6. class Student { int id; String name; } class TestStudent1 { public static void main(String args[]) { Student s1=new Student(); System.out.println(s1.id); System.out.println(s1.name); } }
  • 7. OBJECT An entity that has state and behavior is known as an object e.g., a chair, bike, marker, pen, table, car, etc. It can be physical or logical. An object is an instance of a class. For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so writing is its behavior.
  • 8. OBJECT Syntax for creating an object: ClassName objectName = new ClassName(arguments); Initializing an object: There are 3 ways to initialize an object in Java. 1. By reference variable 2. By method 3. By constructor
  • 9. 1. Initialize the object through a reference variable.
  • 11. 3. Initialization through Constructors. public class Person { String name; int age; // Constructor Person(String name, int age) { this.name = name; this.age = age; } public static void main(String[] args) { // Initialize using the constructor Person p = new Person("Alice", 30); System.out.println(p.name); // Outputs: Alice System.out.println(p.age); // Outputs: 30 } }
  • 12. Class • It should start with the uppercase letter. • It should be a noun such as Color, Button, System, Thread, etc. • Use appropriate words, instead of acronyms. Example: - public class Employee { //code snippet } JAVA NAMING CONVENTIONS
  • 13. Method • It should start with lowercase letter. • It should be a verb such as main(), print(), println(). • If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as actionPerformed(). Example:- class Employee { //method void draw() { //code snippet } } JAVA NAMING CONVENTIONS
  • 14. Variable • It should start with a lowercase letter such as id, name. • It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore). • If the name contains multiple words, start it with the lowercase letter followed by an uppercase letter such as firstName, lastName. • Avoid using one-character variables such as x, y, z. Example :- class Employee { //variable int id; //code snippet } JAVA NAMING CONVENTIONS
  • 15. The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it. ACCESS SPECIFIER
  • 16. There are four types of Java access modifiers: 1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class. 2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. No keyword required. 3. Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package. 4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. ACCESS SPECIFIER
  • 17. 1. Default Access Modifier Compile time error What is the output?
  • 18. 2. Private Access Modifier What is the output?
  • 19. 3. Protected Access Modifier What is the output?
  • 20. 4. Public Access modifier What is the output?
  • 22. The method in Java or Methods of Java is a collection of statements that perform some specific tasks and return the result to the caller. A Java method can perform some specific tasks without returning anything. Java Methods allows us to reuse the code without retyping the code. In Java, every method must be part of some class that is different from languages like C, C++, and Python. <access_modifier> <return_type> <method_name>( list_of_parameters) { //body } JAVA METHODS
  • 25. A constructor is a special method in a class that is called when an object of that class is created. The primary purpose of a constructor is to initialize the newly created object. • A constructor in Java is a special method that is used to initialize objects. • The constructor is called when an object of a class is created. • Every time an object is created using the new() keyword, at least one constructor is called. JAVA CONSTRUCTORS
  • 26. Object Creation and Constructor Invocation When you use the new keyword to create an object, Java performs several steps: • Memory Allocation: Java allocates memory for the new object. • Constructor Invocation: Java calls a constructor to initialize the newly created object. This is where the object's fields are set up and any initialization logic defined in the constructor is executed. • Initialization: The constructor initializes the object's fields with the provided arguments or default values. JAVA CONSTRUCTORS
  • 28. Rules for creating Java constructor There are two rules defined for the constructor. 1. Constructor name must be the same as its class name 2. A Constructor must have no explicit return type 3. A Java constructor cannot be abstract, static, final, and synchronized JAVA CONSTRUCTORS
  • 29. Types of Java constructors 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_name>() { //code snippet } JAVA CONSTRUCTORS
  • 30. Java Default Constructor class Bike1 { Bike1() { System.out.println("Bike is created"); } public static void main(String args[]) { Bike1 b=new Bike1(); } } JAVA CONSTRUCTORS
  • 31. Java Parameterized Constructor A constructor which has a specific number of parameters is called a parameterized constructor. Why use the parameterized constructor? The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also. Example of parameterized constructor In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. JAVA CONSTRUCTORS
  • 33. Constructor Overloading in Java In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods. Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types. JAVA CONSTRUCTORS
  • 34. class Student5 { int id; String name; int age; Student5(int i,String n) { id = i; name = n; } Student5(int i,String n,int a) { id = i; name = n; age=a; } JAVA CONSTRUCTORS void display() { System.out.println(id+" "+name+" "+age); } public static void main(String args[]) { Student5 s1 = new Student5(111,"Arun"); Student5 s2 = new Student5(222,"Bose",25); s1.display(); s2.display(); } }
  • 35. Copy Constructor There is no copy constructor in Java. However, we can copy the values from one object to another like copy constructor in C++. In this example, we are going to copy the values of one object into another using Java constructor. JAVA CONSTRUCTORS
  • 36. Java Command Line Arguments The java command-line argument is an argument i.e. passed at the time of running the java program. The arguments passed from the console can be received in the java program and it can be used as an input. So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt. JAVA CONSTRUCTORS
  • 37. Example: class A { public static void main(String args[]) { for(int i=0;i<args.length;i++) System.out.println(args[i]); } }
  • 38. NON – ACCESS SPECIFIERS IN JAVA Static Final Abstract Volatile Synchronize Transient etc.,
  • 39. 2. INHERITANCE o Introduction o Single-level inheritance o Multilevel inheritance o Method overriding o Dynamic method dispatch o Abstract classes o Usage of super, final, this, and abstract keyword 39
  • 40. 40
  • 41. WHY DO WE NEED JAVA INHERITANCE? Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can directly use the parent class code. Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the ways by which Java achieves Run Time Polymorphism. Abstraction: The concept of abstract where we do not have to provide all details, is achieved through inheritance. Abstraction only shows the functionality to the user.
  • 42. JAVA INHERITANCE 1. Single Inheritance In single inheritance, a sub-class is derived from only one super class. It inherits the properties and behavior of a single-parent class. Sometimes, it is also known as simple inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is a child class. The class ‘B’ inherits all the properties of the class ‘A’.
  • 43. class Single { static int num1=10; static int num2=5; } class Inherit extends Single { public static void main(String[] args) { int num3=2; int result=num1+num2+num3; System.out.println("Result of child class is "+result); } }
  • 44. JAVA INHERITANCE 2. Multilevel Inheritance In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also acts as the base class for other classes. In the below image, 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.
  • 45. Class X { public void methodX() { System.out.println("Class X method"); } } Class Y extends X { public void methodY() { System.out.println("class Y method"); } } Class Z extends Y { public void methodZ() { System.out.println("class Z method"); } public static void main(String args[]) { Z obj = new Z(); obj.methodX(); //calling grand parent class method obj.methodY(); //calling parent class method obj.methodZ(); //calling local method } }
  • 46. JAVA INHERITANCE 3. Hierarchical Inheritance In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image, class A serves as a base class for the derived classes B, C, and D.
  • 49. JAVA INHERITANCE 4. Multiple Inheritance (Through Interfaces) In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Java does not support multiple inheritances with classes. In Java, we can achieve multiple inheritances only through Interfaces. Class C is derived from interfaces A and B.
  • 50. JAVA INHERITANCE 5. Hybrid Inheritance It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple inheritances with classes, hybrid inheritance involving multiple inheritance is also not possible with classes. In Java, we can achieve hybrid inheritance only through Interfaces if we want to involve multiple inheritance to implement Hybrid inheritance.
  • 51. METHOD OVERRIDING If subclass (child class) has the same method as declared in the parent class, it is known as Method Overriding.
  • 52. class Vehicle { void run() {System.out.println("Vehicle is running"); } } class Bike2 extends Vehicle { void run() { System.out.println("Bike is running safely"); } public static void main(String args[]) { Bike2 obj = new Bike2(); obj.run(); }
  • 53. METHOD OVERLOADING If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. If we have to perform only one operation, having same name of the methods increases the readability of the program.
  • 54. class Adder { static int add(int a, int b) { return a+b; } static double add(double a, double b) { return a+b; } } class TestOverloading2 { public static void main(String[] args) { System.out.println(Adder.add(11,11)); System.out.println(Adder.add(12.3,12.6)); }
  • 56. METHOD OVERLOADING VS METHOD OVERRIDING
  • 57. DYNAMIC METHOD DISPATCH •Dynamic method dispatch in Java is a mechanism that allows a Java program to call methods on objects at runtime based on the object's actual type, not the type of the reference used to call the method. This is an example of polymorphism in action. •Dynamic Method Dispatch allows the JVM to determine which method implementation to call at runtime based on the actual object type, not the type of the reference. •It’s used to achieve runtime polymorphism •.
  • 58. How It Works Base Class and Subclasses: You have a base class (superclass) and one or more subclasses. Method Overriding: The subclass overrides a method from the base class. Reference Variable: You use a base class reference to hold an object of the subclass. Method Call: When you call the method using the base class reference, the JVM looks at the actual object type (subclass) and calls the overridden method in that subclass.
  • 61. ABSTRACT AND SUPER Abstraction in Java Abstraction is a process of hiding the implementation details and showing only functionality to the user. For example Sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. Abstraction lets you focus on what the object does instead of how it does it. Abstract class in Java A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated. •.
  • 62. ABSTRACT AND SUPER Points to Remember • An abstract class must be declared with an abstract keyword. • It can have abstract and non-abstract methods. • It cannot be instantiated. • It can have constructors and static methods also. • It can have final methods which will force the subclass not to change the body of the method. Example of abstract class abstract class A { } •.
  • 63. Abstract Method in Java A method which is declared as abstract and does not have implementation is known as an abstract method. Example of abstract method abstract void printStatus(); //no method body and abstract Example: abstract class Animal { public abstract void sound(); } public class Dog extends Animal { public void sound() { System.out.println(“Bark"); } public static void main(String args[]) { Animal obj = new Dog(); obj.sound(); } }
  • 64. ABSTRACT AND SUPER SUPER The super keyword is used in object-oriented programming languages like Java and C++ to refer to the superclass (parent class) of the current object. It can be used to access superclass methods, constructors, and variables, especially when they are overridden or hidden by the subclass (child class).
  • 67. Usage of Java super Keyword 1. super can be used to refer immediate parent class instance variable. 2. super can be used to invoke immediate parent class method. 3. super() can be used to invoke immediate parent class constructor. super is used to refer immediate parent class instance variable. super can be used to invoke parent class method. super is used to invoke parent class constructor
  • 68. FINAL AND THIS Final Keyword In Java The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: 1. variable 2. method 3. class The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. •.
  • 69. FINAL AND THIS 1) Java final variable - If you make any variable as final, you cannot change the value of final variable(It will be constant). •.
  • 71. FINAL AND THIS 2) Java final method If you make any method as final, you cannot override it. •.
  • 73. FINAL AND THIS 3) Java final class - If you make any class as final, you cannot extend it. •.
  • 75. this keyword In java, this is a reference variable that refers to the current object. Usage of java this keyword 1. this can be used to refer current class instance variable. 2. this can be used to invoke current class method (implicitly) 3. this() can be used to invoke current class constructor. 4. this can be passed as an argument in the method call. 5. this can be passed as argument in the constructor
  • 77. 3. PACKAGE o Define package o Access protection/modifiers o Importing packages o Lang package – wrapper class o File input stream and output stream 77
  • 78. 78 3. PACKAGE In Java, a package is a namespace that organizes a set of related classes and interfaces. Packages help avoid naming conflicts and can control access to classes, methods, and variables. They also provide a way to group related code together, making it easier to manage large codebases.
  • 79. 79 JAVA IN-BUILT PACKAGES/ JAVA API PACKAGES • java.lang  Core classes  Fundamental classes such as Object, String, Math, Thread, and System. • java.io  Input and Output  classes for input and output operations like File, InputStream, OutputStream, and Reader. • java.util  Utility classes  Utility classes including collections (ArrayList, HashMap), date and time utilities, and more. • java.applet  Applets  to implement applet programs Package name  Purpose  Description
  • 80. 80 • java.awt  AWT  Classes for GUI creation and graphics, including Frame, Button, and Graphics. • java.net  Networking  Classes for developing network programs, including Socket, ServerSocket, URL, and HttpURLConnection • java.sql  Java Database Connectivity  Classes related to database access • javax.swing  Swings  These classes provide easy-to- use and flexible components for building GUI. The components in this package are referred to as Swing components Package name  Purpose  Description
  • 81. 81 • Find out 5 important classes from each package along with their description
  • 82. 82 IMPORTING BUILTIN PACKAGES import java.util.*; //all classes(entire package) import java.util.Vector; //import Vector class from util package import.java.awt.*; //all the classes of awt will be imported not the sub-package import.java.awt.event.*; //imports the sub package and all its classes
  • 83. 83 DEFINING USER DEFINED PACKAGES Syntax package packagename; Example: package pkg1;
  • 84. 84 STEPS FOR CREATING USER DEFINED PACKAGES Step 1: Create a program which is a part of the defined package (here it is pack1). Step 2: Place your file (Greeting.java) in any drive/ folder path and compile the program
  • 85. 85 Lets use a command and place the above in D drive cd..  d:  D: > javavc –d . Greeting.java The Pack1 directory will be created automatically by the compiler. Step 3: Create another file Greeting2.java in pack2 package Step 4: you can import the defined package here.
  • 86. 86
  • 87. 87 JAVA WRAPPER CLASS • In Java, wrapper classes are used to convert primitive data types into objects. • This is important because Java collections (like ArrayList and HashMap) and some methods require objects rather than primitive types. • We use wrapper classes while working with those data structures where primitive types cannot be used.
  • 88. 88 • Each primitive data type has a corresponding wrapper class in the java.lang package:
  • 89. 89 • Key Concepts 1.Autoboxing and Unboxing Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class when needed, and unboxing is the reverse process. This conversion happens automatically, so you don't usually have to do it manually. Autoboxing Example: Integer integerObject = 5; // int 5 is automatically converted to Integer. Unboxing Example: int primitiveInt = integerObject; // Integer is automatically converted to int
  • 90. 90 class Unboxing { public static void main(String[] args) { Integer x = 10; System.out.println(x); int i = 20; Integer y = new Integer(i); System.out.println(); } }
  • 91. 4. INTERFACES o Defining an interface o Implementing interfaces o Variables in interfaces o Extending interfaces 91
  • 92. INTERFACES An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract methods. It is used to achieve abstraction and multiple inheritances in Java. In other words, interfaces primarily define methods that other classes must implement. Traditionally, an interface could only have abstract methods (methods without a body) and public, static, and final variables by default. In Java, the abstract keyword applies only to classes and methods, indicating that they cannot be instantiated directly and must be implemented.
  • 93. INTERFACES Syntax for Java Interfaces why use interfaces when we have abstract classes? The reason is, abstract classes may contain non-final variables, whereas variables in the interface are final, public, and static.
  • 94. INTERFACES Relationship Between Class and Interface A class can extend another class, and similarly, an interface can extend another interface. However, only a class can implement an interface, and the reverse (an interface implementing a class) is not allowed.
  • 96. 96 INTERFACES Implementation: To implement an interface, we use the keyword implements
  • 97. 97
  • 98. 98
  • 99. INTERFACES Multiple Inheritance in Java Using Interface Multiple Inheritance is an OOPs concept that can’t be implemented in Java using classes.
  • 100. 100
  • 101. 101 Output  Implementation of methodA Implementation of methodB
  • 102. 102 IMPORTANT POINTS IN JAVA INTERFACEST POINTS IN JAVA INTERFACES • We can’t create an instance (interface can’t be instantiated) of the interface but we can make the reference of it that refers to the Object of its implementing class. • A class can implement more than one interface. • An interface can extend to another interface or interface (more than one interface). • A class that implements the interface must implement all the methods in the interface. All the methods are public and abstract. All the fields are public, static, and final. • It is used to achieve multiple inheritances.
  • 103. 103 • It is used to achieve loose coupling. • Inside the Interface not possible to declare instance variables because by default variables are public static final. • Inside the Interface, constructors are not allowed. • Inside the interface main method is not allowed. • Inside the interface, static, final, and private methods declaration are not possible.