0% found this document useful (0 votes)
3 views154 pages

Java Unit II

The document provides an overview of constructors in Java, detailing their purpose, types, and properties. It explains the differences between constructors and methods, introduces the concept of destructors, and discusses the role of garbage collection in memory management. Additionally, it covers static variables, methods, and blocks in Java.

Uploaded by

dharanifaceprep
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views154 pages

Java Unit II

The document provides an overview of constructors in Java, detailing their purpose, types, and properties. It explains the differences between constructors and methods, introduces the concept of destructors, and discusses the role of garbage collection in memory management. Additionally, it covers static variables, methods, and blocks in Java.

Uploaded by

dharanifaceprep
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

OOP Java is the easiest, scoring and my

favorite subject

JAVA - UNIT II
OOP Java is the easiest, scoring and my
favorite subject

Constructor
Constructor
1. class Cube{
🞂 A constructor in Java is a special type of method that is used to
OOP Java is the easiest, scoring and my

initialize objects. 2. instance


favorite subject
variable1
3. instance variable1
🞂 The constructor is called when an object of a class is created.
4. …
🞂 A constructor initializes an object immediately
5. upon creation.
Cube()
🞂 It has the same name as the class in which 6. it resides
{ and is
syntactically similar to a method. 7. //initailze
🞂 JVM first allocates the memory for variables (objects) and then
executes the constructor to initialize instance variables.
object }
🞂 The JVM calls it automatically when we create an object.
8. } //class
🞂 A constructor defines what happens when an object of a class is
created.
Properties of constructor
🞂 Constructor is invoked automatically whenever1. class Demo{
an object of
OOP Java is the easiest, scoring and my

class is created. 2. instance


favorite subject
variable1
3. instance variable1
🞂 Constructors do not have return types and they cannot return
4. …
values, not even void.
5. Demo()
🞂 All classes have constructors by default: if 6.
you do not{ create a
class constructor yourself, Java creates one [Link] you //initailze
known as
default constructor.
🞂 Constructor is a method that is called at runtime during the
object creation by using the new operator. object
The JVM} calls it
automatically when we create an object. 8. } //class
🞂 It is called and executed only once per object.
🞂 It means that when an object of a class is created, constructor
is called. When we create 2nd object then the constructor is
again called during the second time.
Types of Constructor

Construct
OOP Java is the easiest, scoring and my
favorite subject

or

No- Parameteriz Copy


Default
Argument ed Constructor
OOP Java is the easiest, scoring and my
favorite subject

Default Constructor
Default Constructor: [Link]
1. class MyConst {
OOP Java is the easiest, scoring and my

2. public static void main(String[] args) {


favorite subject

3. MyConst c=new MyConst();


4. }
5. } pi After
m
Co r Compilation
le 1. class MyConst{
2. MyConst(){
3. //Default
Constructor…
4. }
5. public static void main(String[]
args) {
6. c=new MyConst();
7. }
Default Constructor
🞂 Once you define your own constructor, the default constructor is
OOP Java is the easiest, scoring and my
favorite subject

no longer used.
🞂 The default constructor automatically initializes all instance
[Link] to zero.
class MyAccount{ 8. class MyBank {
2. int accNo;
Example: 9. public static void main(String[] args){
3. double balance; 10. MyAccount ma= new MyAccount();
4. MyAccount(){ 11.
[Link]("balance="+[Link]);
5. //default constructor
12. }//main()
6. }
13.}//class
7. }//class
Outp
ut
balance=0.0
OOP Java is the easiest, scoring and my
favorite subject

No-Argument
Constructor
No-Argument Constructor: [Link]
[Link] MyMain{
1. class Cube { OOP Java is the easiest, scoring and my

[Link] static void


favorite subject

2. double width; main(String[] args){


3. double height; 15. Cube c=new
4. double depth; Cube();
5. Cube() 16. }
6. { 17.}
7. [Link]("
If you implement any constructor then you no
Constructing cube"); longer receive a default constructor from Java
8. width = 10; compiler.

9. height = 10;
10. depth = 10;
11. }//Cube()
12.}//class
OOP Java is the easiest, scoring and my
favorite subject

Parameterized
Constructor
Parameterized Constructor: [Link]
[Link] MyMain{
1. class Cube { OOP Java is the easiest, scoring and my

[Link] static void


favorite subject

2. double width, height, depth; main(String[]


3. Cube(double w, double h, double d) args){
4. { [Link](" 12. Cube c=new
Constructing cube"); Cube(10,10,10);
5. width = w; 13. }
6. height = h; 14.}
7. depth = d;
8. }//Cube()
9. }//class
Parameterized Constructor: [Link] with method
[Link] MyMain{
1. class Cube { OOP Java is the easiest, scoring and my
[Link] static void
favorite subject

2. double width,height,depth; main(String[]


3. Cube(double w, double h, double d) args){
4. { [Link]("Constructing15.
cube"); Cube c=new Cube(10,10,10
5. width = w; 16. [Link]();
6. height = h; 17. }
7. depth = d; 18.}
8. }//cube()
9. void calVolume(){
10. [Link]("Volume="
+width*height*depth);
11. } //calVolume()
12.} //class
Parameterized Constructor: method with return value
[Link] MyMain{
1. class Cube { OOP Java is the easiest, scoring and my
[Link] static void
favorite subject

2. double width,height,depth; main(String[] args){


3. Cube(double w, double h, double d) 15. double vol;
4. { [Link]("[Link]
cube");c=new Cube(10,10,10);
5. width = w; 17. vol=[Link]();
6. height = h; 18. [Link]("
7. depth = d;
Volume="+vol);
8. }//cube()
19. }
9. double calVolume(){
20.} Outp
10. return width*height*depth; ut
11. }//calVolume() Constructing
12.}//class cube
Volume=1000.0
OOP Java is the easiest, scoring and my
favorite subject

Copy Constructor
Copy Constructor
🞂 It is a special type of constructor that is Constructor
used to create a new
2(Constructor
OOP Java is the easiest, scoring and my

Constructor 1()
favorite subject

object using the existing object of a class 1)


that had been created
{
previously. {


🞂 It creates a new object by initializing }} the object with the
instance of the same class.
Copy
Constructor
Copy Constructor: [Link]
19. class MyProgramCopy {
1. class Student{ 20. public static void main(String[]
OOP Java is the easiest, scoring and my
favorite subject

2. String name; args){


3. int rollno; 21. float area;
4. Student(String s_name, int s_roll){
22. Student s1=new
5. [Link]("ConstructorInvoked");
Student("darshan",101);
6. [Link]=s_name; 23. //invoking Copy Constructor
7. [Link]=s_roll; 24. Student s2=new Student(s1);
8. } //Constructor1 25. [Link]();
26. [Link]();
9. Student(Student s){ //CopyConstructor
27. } //main()
10. [Link]("CopyConstructor 28. } //class myProgram
Invoked"); Outp
11. [Link]=[Link]; ut
12. [Link]=[Link]; Constructor Invoked
13. } //Constructor2 CopyConstructor
Invoked
14. public void display(){ name=darshan
15. [Link]("name="+name); rollno=101
16. [Link](" rollno="+rollno); name=darshan
17. } // display() rollno=101
Advantages of Copy Constructor
🞂 It is easier to use when our class contains Constructor
a complex2(Constructor
object with
OOP Java is the easiest, scoring and my

Constructor 1()
favorite subject

various parameters. 1)
{
{
🞂 Whenever we need to add all the field ……of a class to another
object, then just send the reference of } previously created
}
object.
Copy
🞂 One of the most importance of copy constructors is that there is
Constructor
no need for any typecasting.
🞂 Using a copy constructor, we can have complete control over
object creation.
🞂 With Copy Constructor, we can pass object of the class as a
parameter(pass by reference).
OOP Java is the easiest, scoring and my
favorite subject

Constructor
Overloading
Constructor Overloading
1.🞂class
In addition
Balance{ to overloading normal methods,
1. class Account{ you can also
OOP Java is the easiest, scoring and my
favorite subject

2. overload int constructor


accNo; methods. 2. public static void
3. double bal; main(String
4. Balance(){ args[]){
5. [Link]("inside
3. Balance b1= new Balance();
const1"); 4. Balance b2= new Balance(100);
6. bal=0; 5. Balance b3=new
7. } Balance(1201,10000);
8. Balance(double b){ 6. [Link]("[Link]="+[Link]
9. [Link]("inside
l);
const2"); 7. [Link]("[Link]="+[Link]
10. bal=b; l);
11. } 8. [Link]("[Link]="+[Link]
12. Balance(int a,double b){ l+
13. [Link]("inside
"[Link]="+[Link]);
const3"); 9. }
14. bal=b; 10.}
15. accNo=a;
Why Constructor?
🞂 The pivotal purpose of constructor is to initialize the instance
OOP Java is the easiest, scoring and my
favorite subject

variable of the class.


🞂 We use constructors to initialize the object with the default or
initial state.
🞂 Through constructor, we can request the user of that class for
required dependencies.
🞂 A constructor within a class allows constructing the object of
the class at runtime.
🞂 Allocates appropriate memory to objects.
🞂 If we need to execute some code at the time of object creation,
we can write them inside the constructor.
🞂 Example:
⮩ If we talk about a Cube class then class variables are width, height
and depth.
When to use Constructor?
🞂 When we need to execute some code at the time of object
OOP Java is the easiest, scoring and my
favorite subject

creation.
🞂 Used for the initialization of instance variables.
🞂 To assign the default value to instance variables.
🞂 To initializing objects of the class.
Constructor() vs. Method()
Constructor() Method()
OOP Java is the easiest, scoring and my
Naming Constructor name must be same as class Method name can be anything.
favorite subject

name.
Return types Constructor does not have any return type, Method must have return types, at least
not even void. void.
Call Constructor can be invoked implicitly when Method is called by the programmer.
object is created. Invoked explicitly.
Purpose To initialize an object To execute the code
Inheritance Constructor cannot be inherited by Method can be inherited by subclass.
subclass.
OOP Java is the easiest, scoring and my
favorite subject

Destructor
Destructor
🞂 Destructor is the opposite to the constructor. Constructor is
OOP Java is the easiest, scoring and my
favorite subject

used to initialize objects while the destructor is used to delete


or destroy the object that releases the resource occupied by the
object.
🞂 Definition: Destructor is an instance member function which is
invoked automatically whenever an object is going to be
destroyed.
🞂 In other words, a destructor is the last function that is going to
be called before an object is destroyed.
🞂 In java, there is a special method named garbage collector that
automatically called when an object is no longer used.
🞂 When an object completes its life-cycle the garbage collector
deletes that object and de-allocates or releases the memory
occupied by the object.
🞂 In C++, dynamically allocated objects must be manually
Destructor
Why Destructor? OOP Java is the easiest, scoring and my
favorite subject

⮩ When we create an object of the class(using new), it occupies some space in the
memory. If we do not delete these objects, it remains in the memory and occupies
unnecessary space.
⮩ To resolve this problem, we use the destructor.
🞂 Remember that there is no concept of destructor in Java.
🞂 Instead of destructor, Java provides the garbage collector that
works the same as the destructor.
🞂 The garbage collector is a program (thread) that runs on
the JVM. It automatically deletes the unused objects (objects
that are no longer used) and free-up the memory.
🞂 The programmer has no need to manage memory, manually.
Working of garbage collector(destructor) in java

🞂 When the object is created it occupies the space in the heap.


OOP Java is the easiest, scoring and my
favorite subject

These objects are used by the threads.


🞂 If the objects are no longer used by the thread it becomes
eligible for the garbage collection.
🞂 The memory occupied by that object is now available for new
objects that are being created.
🞂 When the garbage collector destroys an object, the JRE calls
finalize() method to close the connections such as database and
network connection.
OOP Java is the easiest, scoring and my
favorite subject

Static
Static in java

OOP Java is the easiest, scoring and my


favorite subject

Static in Java

Static Variable Static Method Static Block Static Class


Static

🞂 The static keyword is used for memory management. OOP Java is the easiest, scoring and my
favorite subject
🞂 We can apply static keyword with variables, methods, blocks and nested classes.
🞂 The static keyword belongs to the class than an instance of the class.
🞂 The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
Static Variable

🞂 Static variables have a property of preserving their value even after they are out of their scope.
OOP Java is the easiest, scoring and my
favorite subject
🞂 The static variable gets memory only once in the class area at the time of class loading.
🞂 Advantage of static variable: It makes program memory efficient (static variable saves memory).
🞂 Characteristics of static variable:
⮩ It is initialized to zero when the first object of its class is created. No other initialization is allowed.
⮩ Only one copy of that member is created for the entire class and is shared by all the objects of that class, no
matter how many objects are created.
⮩ It is visible only within the class, but its lifetime is the entire program.
⮩ Static variables are normally used to maintain values common for all objects.
⮩ The class constructor does not initialize static variable.
Static vs Non-Static Function

[Link](Non-static [Link](static
function) function)
OOP Java is the easiest, scoring and my

1. public class MyProgram { 1. public class MyProgram {


favorite subject

2. public static void 2. public static void


main(String[] main(String[]
args) { args) {
3. int a=1,b=2,c; 3. int a=1,b=2,c;
4. MyProgram mp=new 4. c = add(a,b);
5. [Link](c);
MyProgram(); 6. }//main
5. c = [Link](a,b);

6. 7. static int add(int i,int


[Link](c); }/ j)
/main 8. { return i
7. public int add(int i,int + j;
j) 9. }
8. { 10.}//class
9. return i + j;
10. }
Characteristic of static method

🞂 A static method can call only other static methods and can not call a non-static method from it.
OOP Java is the easiest, scoring and my
favorite subject
🞂 A static method can be accessed directly by the class name and doesn’t need any object
🞂 A static method cannot refer to “this” or “super” keywords in anyway
Static Method: WAP using class Rectangle and calculate area

[Link] MyRectangle {
OOP Java is the easiest, scoring and my

1. import [Link].*; favorite subject

[Link] static void main(String[] args)


2. class Rectangle{
{
3. static float height;
15. Rectangle r1= new Rectangle();
4. static float width;
5. static void calArea() {
16. Scanner sc= new Scanner([Link]);
6. [Link]( "Area= "

17. [Link]("enter height:");


+height*width);
7. Outp
} //calArea()
ut 18. [Link]=[Link]();
enter
8. } //class height:30.55
19. [Link]("enter width:");
enter width:20.44
Area=624.442
20. [Link]=[Link]();
static keyword

🞂 static keyword is mainly used for memory management. OOP Java is the easiest, scoring and my
favorite subject
🞂 It can be used with
⮩ Variables
⮩ Methods
⮩ Blocks
⮩ Nested classes
🞂 Basically, static is used for a constant variable or a method that is same for every instance of a class.
🞂 The static variable can be used to refer to the common property of all objects.
🞂 The static variable gets memory only once in the class area at the time of class loading.
🞂 It makes your program memory efficient.
🞂 Syntax
static type variablename;
class Student {
int rollNo; OOP Java is the easiest, scoring and my

static String
String collegecollege
= =
favorite subject
student1 student2 student3
.
"DIET";
. rollN
. o
} nam
e
colleg DIET DIET DIET
class StudentDemo { e
public static void main(String
args[]) { colleg DIET
Student student1 = new e
Student();
Student student2 = new
Student();
Student student3 = new
Student();
.
.
.
}
}
static method

🞂 If you apply static keyword with any method, it is knownOOPas static method.
Java is the easiest, scoring and my
favorite subject
🞂 A static method belongs to the class rather than the object of a class.
🞂 A static method can be invoked without the need for creating an instance of a class.
🞂 A static method can access static data member and can change the value of it.
🞂 Restrictions
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
class Student {
int rollno;
String name;
static String college="abc";
OOP Java is the easiest, scoring and my
favorite subject

static void change() {


college = "DIET"; We can not use non-static
rollno = 10; variables in static
} methods
Student(int r, String n) {
rollno = r;
name = n;
}
void display() {
[Link](rollno+" "+name+" "+college);
}
}
class TestStaticMethod {
public static void main(String args[]) {
[Link]();
Student s1 = new Student(111,"Tom");
Student s2 = new Student(222,"Jerry");
[Link]();
[Link]();
}
Static Block

🞂 Static block is executed exactly once, when the class is first loaded.
OOP Java is the easiest, scoring and my
favorite subject
🞂 It is used to initialize static variables of the class.
🞂 It will be executed even before the main() method.
🞂 Syntax

🞂 How to call static block in java?


⮩ Unlike method, there is no specified way to call a static block.
⮩ The static block executes automatically when the class is loaded in memory.

static {
//initialisation of static
variables…
}
Example: Static Block, Method and Variable

1. class StaticDemo {
2. static int a = 4; //static variable declared & initialized
OOP Java is the easiest, scoring and my
favorite subject

3. static int b; //static variable


3 declared
4. static void dispValue(int x) {
5. [Link]("Static method initialized.");
6. [Link]("x = " + x);
7. [Link]("a = " + a);
8. [Link]("b = " + b);
9. } //static method
10. static { Outp
11. [Link]("Static block 1initialized.");
ut
12. b= a * 5; Static block
13. } //static block 2
initialized.
inside main()...
14. public static void main(String args[]) {
Static method
15. [Link]("inside main()...");
initialized.
16. dispValue(44); x = 44
17. } //main() a = 4
Points to remember for static keyword

1. When we declare a field static, exactly a single copy of that field is created and shared among all
OOP Java is the easiest, scoring and my
instances of that class. favorite subject

2. Static variables belong to a class, we can access them directly using class name. Thus, we don't need
any object reference.
3. We can only declare static variables at the class level.
4. We can access static fields without object initialization.
5. Static methods can't be overridden.
6. Abstract methods can't be static.
7. Static methods can't use this or super keywords.
8. Static methods can't access instance variables and instance methods directly. They need some object
reference to do so.
9. A class can have multiple static blocks.
Mutable and Immutable Objects

🞂 The content of mutable object can be changed, while content of immutable objects can not be changed.
OOP Java is the easiest, scoring and my
favorite subject

class MutableClass{ class ImmutableClass{


int a; int a;
void add5() { int add5() {
a = a + 5; return ( a + 5 );
} }
} }
public class MutableClassDemo { public class MutableClassDemo {
public static void main(String[] public static void main(String[] args)
args) { {
MutableClass m1 = new ImmutableClass m1 = new
MutableClass(); ImmutableClass();
m1.a = 10; m1.a = 10;
m1.add5(); int ans = m1.add5();
[Link](m1.a); [Link]("A in m1 = " +
} m1.a);
} [Link]("returned = " +
ans);
Passing Objects as Argument

class Time{
🞂 In order to understand howint
andhour;
why we need to pass OOP
object as an argument in methods, lets see the
Java is the easiest, scoring and my
below example. int minute; favorite subject

int second;
public Time(int hour, int minute, int
second) {
[Link] = second;
[Link] = minute;
[Link] = hour;
} public class TimeDemo {
void add(Time t) { public static void main(String[]
[Link] += [Link]; args) {
if([Link]>=60) { Time t1 = new Time(11,59,55);
[Link]++; Time t2 = new Time(0,0,5);
[Link]-=60;
} [Link](t2);
[Link] += [Link];
if([Link]>=60) { [Link]([Link] + ":"
[Link]++; + [Link] + ":" + [Link]);
[Link]-=60; }
} }
[Link] += [Link];
}
}
Array of Objects

🞂 We can create an array of object in java. OOP Java is the easiest, scoring and my
favorite subject
🞂 Similar to primitive data type array we can also create and use arrays of derived data types (class).

class Student{ public class ArrayOfObjectDemo {


int rollNo; public static void main(String[]
String name; args) {
Student[] stu = new Student[3];
public Student(int rollNo, String
name) { stu[0] = new
[Link] = rollNo; Student(101,"darshan");
[Link] = name; stu[1] = new Student(102, "OOP");
} stu[2] = new Student(103,"java");

void printStudentDetail() { stu[0].printStudentDetail();


[Link]("| "+ stu[1].printStudentDetail();
rollNo stu[2].printStudentDetail();
+" | -- | "+ }
name +" |"); }
}
Access Control
Modifier Sam Same Same Differ
OOP Java is the easiest, scoring and my
favorite subject
Differe
e Packa Packa ent nt
Clas ge ge Packa Packag
s Sub Non ge e
Class Sub Sub Non
Class Class Sub
Class
Private
Default
Protected
Public
Programs
🞂 Write a class named Rectangle to represent a rectangle. It
OOP Java is the easiest, scoring and my
favorite subject

contains following members:


Data: width (double) and height (double) that specify the width
and height of the rectangle.
Methods:
1. A no-arg constructor that creates a default rectangle.
2. A constructor that creates a rectangle with the specified
width and height.
3. A method named getArea() that returns the area of this
rectangle.
4. A method named getPerimeter() that returns the perimeter.
🞂 Write a program to create circle class with area function to find
area of circle.
🞂 Define time class with hour and minute. Also define addition
method to add two time objects.
🞂 Declare a class called student having following data
OOP Java is the easiest, scoring and my
favorite subject

Nested Class
Nested Class

🞂 Nested Class: Class within another class


🞂 Scope: Nested class is bounded by the scope of its enclosing class. OOP Java is the easiest, scoring and my
favorite subject

⮩ E.g. class B is defined within class A, then B is known to A, but not outside of A.
🞂 A nested class has access to the members, including private members of the class in which it is nested.
🞂 However, the enclosing class does not have access to the members of the nested class. i.e. Class B can access private member
of class A, while reverse is not accessible.

A: Outer
Class

B:
Nested
Class
Nested Class

OOP Java is the easiest, scoring and my


favorite subject
Nested Class

🞂 Types of Nested class:


OOP Java is the easiest, scoring and my
favorite subject

Nested Class

Static Non- Static


Nested Class Nested Class
Non-Static Nested Class: [Link]

1. class Outer{ 16. class InnerOuterDemo{


2. private int a=100;//instance variable 17. public static void
OOP Java is the easiest, scoring and my
favorite subject

3. void outerMeth(){ main(String[]


4. Inner i= new Inner(); args)
5. 18.
[Link]("inside outerMeth()...");{
6. [Link](); 19. Outer o=
7. } new Outer();
8. class Inner{ 20.
[Link]();
9. int b=20;
21. }
10. void innerMeth(){
22. } //InnerOuterDemo
11. [Link]("inside innerMeth()..."
12. +(a+b));
13. }
Outp
14. } //inner class ut
15. } //outer class inside outerMeth()...
inside
innerMeth()...120
Static Nested Class: InnerOuterDemo
error: non-static variable a
1. class Outer{ cannot be referenced from 16. class InnerOuterDemo{
static int
int a=100;//instance
2. a static context 17. public static void
OOP Java is the easiest, scoring and my
a=100;
variable favorite subject

3. void outerMeth(){ main(String[]


4. Inner i= new Inner(); args)
5. 18.
[Link]("inside outerMeth()...");{
6. [Link](); 19. Outer o=
7. } new Outer();
8. static class Inner{ 20.
[Link]();
9. int b=20;
21. }
10. void innerMeth(){
22. } //InnerOuterDemo
11. [Link]("inside innerMeth()..."
12. +(a+b));
13. }
Outp
14. } //inner class ut
15. } //outer class inside outerMeth()...
inside
innerMeth()...120
Points to remember: Inner class

🞂 Inner class implements a security mechanism in Java.


🞂 Reduces encapsulation, more organized code by logically grouping
OOPthe
Java is classes.
the easiest, scoring and my
favorite subject

A: Outer
Class

B:
Nested
Class
OOP Java is the easiest, scoring and my
favorite subject

thi
s

‘this’ keyword
class Box {
double length;
double breadth;
double height;
Box(double l, double b, double h) { OOP Java is the easiest, scoring and my
favorite subject
[Link]("Constructing Box");
length = l;
breadth = b;
height = h;
}
void volume() {
double volume = length * breadth * height;
[Link]("Volume is " + volume);
}
}
class BoxDemo {
public static void main(String args[]) {
Box myBox1 = new Box(10,20,30);
Box myBox2 = new Box(3,6,9);
[Link]();
[Link]();
}
}
Box(double length, double breadth, double
height) { = length;
[Link]
length = length; length is instance
Creates ambiguity for
[Link] = breadth;variable as well as length
breadth = breadth; compiler of
[Link] = height;
height = height; is formal parameter
method
‘this’ Keyword
🞂 this is a reference variable that refers to the current object.
OOP Java is the easiest, scoring and my
favorite subject

🞂 this can be used to invoke current object's method.


🞂 this() can be used to invoke current class constructor
🞂 this can be passed as a parameter to constructor and method
call.
🞂 this can be used to return the current object from the method.

Thi
s
OOP Java is the easiest, scoring and my
favorite subject

Inheritance
Inheritance

OOP Java is the easiest, scoring and my


favorite subject
Inheritance
class
class Doctor class Footballer
Businessman
Attributes: Attributes: Attributes:
OOP Java is the easiest, scoring and my

🞂 All of the Age,


favorite subject

classes have common


Height, Age,attributes
Height, (Age,Age,
Height, Weight) and methods
Height,
(Walk, Talk, Eat).
Weight Weight Weight
they have some Methods:
🞂 However, Methods: special skills likeMethods:
Diagnose, Playfootball and
Runbusiness.
Talk() Talk() Talk()
🞂 In each ofWalk() Walk()
the classes, you would be copying theWalk()
same code for Walk, Talk and
Eat()
Eat for each character. Eat() Eat()
Diagnose() Playfootball() Runbusiness()
Inheritance
🞂 The mechanism of a class to derive properties and characteristics from
OOP Java is the easiest, scoring and my
favorite subject

another class is called Inheritance.


🞂 It is the most important feature of Object Oriented Programming.
🞂 Inheritance is the process, by which class can acquire(reuse) the properties
and methods of another class.
🞂 Base Class: The class whose properties are inherited by sub class is called
Base Class/Super class/Parent class.
🞂 Derived Class: The class that inherits properties from another class is called
Sub class/Derived Class/Child class.
🞂 Inheritance is implemented using super class and sub class relationship in
Base Class
object-oriented languages.

Derived
Class
Inheritance
class
Person is
OOP Java is the easiest, scoring and my
favorite subject

class Person
Attributes: called
Age, Height, Base
Weight class
Methods:
Talk() , Walk(),
Eat()
class
class Doctor class Footballer
Businessman
Methods: Methods: Methods:
Diagnose() Playfootball() Runbusiness()

These classes
are called
Derived
class
Inheritance
OOP Java is the easiest, scoring and my
favorite subject

class Vehicle
Attributes:
Engine_no,
color
Methods:
apply_breaks()

class Car class Bus class Truck


Attributes: Attributes: Attributes:
Private_vehicle Public_vehicle Goods_vehicle
Inheritance: Advantages
🞂 Promotes reusability OOP Java is the easiest, scoring and my
favorite subject

⮩ When an existing code is reused, it leads to less development and maintenance costs.
🞂 It is used to generate more dominant objects.
🞂 Avoids duplicity and data redundancy.
🞂 Inheritance makes the sub classes follow a standard interface.

Base Class

Derived
Class
OOP Java is the easiest, scoring and my
favorite subject

Implementing
Inheritance
Subclass-Superclass Relationship
Introduction
🞂 Inheritance is the process, by which a class can acquire(reuse)
OOP Java is the easiest, scoring and my
favorite subject

the properties and methods of another class.


🞂 The mechanism of deriving a new class from an old class is
called inheritance.
🞂 The new class is called derived class and old class is called base
class.
🞂 The derived class may have all the features of the base class
and the programmer can add new features to the derived class.
🞂 Inheritance is also known as “IS-A relationship” between parent
and child classes.
🞂 For Example :
⮩ Car IS A Vehicle
⮩ Bike IS A Vehicle
⮩ EngineeringCollege IS A College
Inheritance Example
class Vehicle OOP Java is the easiest, scoring and my
favorite subject

Attributes:
Engineno, color
Methods:
applybreaks()

class Car class Bus class Truck


Attributes: Attributes: Attributes:
privatevehicle publicvehicle goodsvehicle
How to implement Inheritance in java
🞂 To inherit a class, you simply incorporate the definition of one
OOP Java is the easiest, scoring and my
favorite subject

class into another by using the extends keyword.


Syntax:

class subclass-name extends superclass-


name {
// body of class…
}
Implementing Inheritance in java

class A
OOP Java is the easiest, scoring and my
favorite subject

{
Class A
//SuperClass or ParentClass or Base Class
BaseClass
} the keyword “extends” is used to create a
subclass of A

class B extends A
Class B
{ Derived Class
//SubClass or ChildClass or
DerivedClass
}
Implementing Inheritance in java
Person
1. class Person OOP Java is the easiest, scoring and my
favorite subject
name:String
2. { Contact:long
3. String name;
4. long contact;
5. }

6. class Employee extends Person


7. { Employee Customer
8. int empID; empID:int customerID:int
9. String designation; Designation:Stri InvoiceNo:int
10.} ng

[Link] Customer extends Person


12.{
13. int customerID;
14. int invoiceNo;
15.}
Implementing Inheritance in java
1. class Person Person
OOP Java is the easiest, scoring and my
favorite subject

2. { name:String
3. String name; Contact:long
4. long contact; dispContact():void
5. public void dispContact()
6. { [Link](“num=”+contact);
7. }
8. }
9. class Employee extends Person
10.{ Employee Customer
11. int empID; empID:int customerID:int
12. String designation; Designation:Stri InvoiceNo:int
13.} ng
[Link] Customer extends Person
15.{
16. int customerID;
17. int invoiceNo;
18.}
OOP Java is the easiest, scoring and my
favorite subject

Property of Inheritance
Property of Inheritance
A class member that has been declared
as private will remain private to its
OOP Java is the easiest, scoring and my
favorite subject

class. It is not
Base class A can’t access accessible by any code outside its class,
attributes and methods of Class A including subclasses.
Derived Class B Base Class

Derived Class B can’t


access private members
of Base class A

Class B
Derived Class Derived Class B can access
attributes and methods of
Base class A
OOP Java is the easiest, scoring and my
favorite subject

Inheritance by Example
Example1: InheritanceDemo1
A OOP Java is the easiest, scoring and my
favorite subject

#i:int
~j:int
showij():void

B
~k:int
showk():void
add():void
Example1: [Link]
[Link] InheritanceDemo{
1. class A{ [Link] static void main(String[]
OOP Java is the easiest, scoring and my
favorite subject

2. protected int i;
3. int j; args)
4. void showij(){ 18. {
5. [Link]("i="+i+" j="+j);
19. A superObjA= new
6. } A();
7. } 20. superObjA.i=10;
21. superObjA.j=20;
8. class B extends A{ //inheritance
9. int k; 22. B subObjB= new
10. void showk(){ B();
11. [Link]("k="+k); 23. subObjB.k=30;
12. }
13. void add(){ 24. Outp
14. [Link]("i+j+k="+(i+j+k)); [Link](); ut
15. } i=10 j=20
25. [Link]();
k=30
16.} 26. [Link]();
i+j+k=30
27. }
Types of Inheritance in Java
1. Single Inheritance 2. Hierarchical 3. Multilevel Inheritance
InheritanceOOP Java is the easiest, scoring and my
favorite subject

A A A

B C B
B

4. Multiple Inheritance 5. Hybrid Inheritance

A Note: Multiple and Hybrid


A B Inheritance is not
supported in Java with the
B C Class Inheritance, we can
C still use those Inheritance
with Interface which we will
D learn in later part of the Unit
OOP Java is the easiest, scoring and my
favorite subject

Single Inheritance B
Single Inheritance: [Link]
[Link] InheritanceDemo{
1. class A{ [Link] static void main(String[]
OOP Java is the easiest, scoring and my
favorite subject

2. protected int i;
3. int j; args)
4. void showij(){ 18. {
5. [Link]("i="+i+" j="+j);
19. A superObjA= new
6. } A();
7. } 20. superObjA.i=10;
21. superObjA.j=20;
8. class B extends A{ //inheritance
A
9. int k; 22. B subObjB= new
10. void showk(){ B();
11. [Link]("k="+k); 23. subObjB.i=100 B
12. } 24. subObjB.j=100;
13. void add(){ 25. Outp
subObjB.k=30;
14. [Link]("i+j+k="+(i+j+k)); ut
15. } i=10 j=20
26. k=30
16.} [Link](); i+j+k=230
27. [Link]();
OOP Java is the easiest, scoring and my
favorite subject

Hierarchical A

Inheritance B C
1. class A{ [Link] C extends A{
2. protected int i; 15. int m;
3. int j; 16. void showm(){
OOP Java is the easiest, scoring and my
favorite subject

4. void showij(){ 17.


5. [Link]("inside
[Link]("inside
class class C:k="+m);
A:i="+i+" j="+j); 18. }
6. } 19. void add_ijm(){
7. } 20.
8. class B extends A{ [Link](i+"+"+j+
9. int k;
10. void showk(){ "+"+m+"="+(i+j+m));
[Link]("inside 21. } A
22.}
class B:k="+k);
B C
11. }
12. void add_ijk(){
InheritanceLev
[Link] InheritanceLevel{
24. public static void main(String[] args) {
InheritanceLev
25. A superObjA= new A(); OOP Java is the easiest, scoring and my [Link]
26. superObjA.i=10; favorite subject

27. superObjA.j=20;
28. [Link]();

29. B subObjB= new B(); A


30. subObjB.i=100;
31. subObjB.j=200;
32. subObjB.k=300; B C
33. [Link]();
34. subObjB.add_ijk();

35. C subObjC= new C(); Outp


ut
36. subObjC.i=1000; inside class A:i=10 j=20
37. subObjC.j=2000;; inside class B:k=300
38. subObjC.m=3000; 100+200+300=600
39. [Link](); inside class C:k=3000
40. subObjC.add_ijm(); 1000+2000+3000=6000
41. }
42.}
OOP Java is the easiest, scoring and my
favorite subject

Multilevel Inheritance
1. class A{ [Link] C extends B{
2. protected int i; 15. int m;
3. int j; 16. void showm(){
OOP Java is the easiest, scoring and my
favorite subject

4. void showij(){ 17.


5. [Link]("inside
[Link]("inside
class class C:k="+m);
A:i="+i+" j="+j); 18. }
6. } 19. void add_ijkm(){
7. } 20.
8. class B extends A{ [Link](i+"+"+j+
9. int k;
10. void showk(){ A
"+"+k+"+"+m+"="+(i+j+k+m));
[Link]("inside 21. }
22.} B
class B:k="+k);
11. } C
12. void add_ijk(){
InheritanceMultil
[Link] InheritanceMultilevel{
24. public static void main(String[] args) { InheritanceMultil
25. A superObjA= new A();
26. superObjA.i=10; [Link]
OOP Java is the easiest, scoring and my
favorite subject

27. superObjA.j=20; A
28. [Link]();

29. B subObjB= new B(); B


30. subObjB.i=100;
31. subObjB.j=200;
C
32. subObjB.k=300;
33. [Link]();
34. subObjB.add_ijk();

35. C subObjC= new C(); Outp


36. subObjC.i=1000; ut
37. subObjC.j=2000; inside class A:i=10 j=20
38. subObjC.k=3000; inside class B:k=300
39. subObjC.m=4000; 100+200+300=600
40. [Link](); inside class C:k=4000
41. subObjC.add_ijkm(); 1000+2000+3000+4000=10000
42. }
OOP Java is the easiest, scoring and my
favorite subject

Derived Class with


Constructor
Derived Class with Constructor
Cube CubeInherit
# height: double OOP Java is the easiest, scoring and my
cw1:CubeWeight
favorite subject

# width: double cw2:CubeWeight


# depth: double
main(): void
Cube()
volume(): double

CubeWeight
# weigth: double
CubeWeight(double, double, double,
double):double
1. class Cube{ [Link] CubeInherit{
2. protected double 23. public static void main(String[]
args) {
OOP Java is the easiest, scoring and my

[Link] cw1= new


favorite subject

height,width,depth; 25.
3. Cube(){ CubeWeight(10,10,10,20.5);
4. [Link] cw2= new
[Link]("inside 27.
5. default CubeWeight(100,100,100,200.5);
Constructor:CUBE"); [Link]("[Link]()="
6. }
7.
[Link] double volume(){
CubeWeight extends Cube{ +[Link]());
8. return
[Link] weigth; [Link]("[Link]()="
height*width*depth;
[Link](double h,double w,double d,
9. double m)} +[Link]());
10.}
14.{ 30. }} Outp
ut
CubeInheri
15. [Link]("inside Constructor:
16.
[Link]
inside default
Constructor:CUBE
CUBEWEIGTH"); inside Constructor:CUBEWEIGTH
17. height=h; inside default
18. width=w; Constructor:CUBE
19. depth=d; inside Constructor:CUBEWEIGTH
OOP Java is the easiest, scoring and my
favorite subject

Super Keyword
Super Keyword
🞂 Whenever a subclass needs to refer to its immediate superclass,
OOP Java is the easiest, scoring and my
favorite subject

it can do so by use of the keyword super. Super has two general


forms:
1. Calls the superclass constructor.
2. Used to access a members(i.e. instance variable or method) of the
superclass.
Using super to Call Superclass Constructors

🞂 Call to super must be first statement in constructor


OOP Java is the easiest, scoring and my
favorite subject

Cube CubeInherit
# height: double cw1:CubeWeight
# width: double cw2:CubeWeight
# depth: double
main(): void
Using
Cube(double,
“super” volume(): double
double, double)

CubeWeight
# weigth: double

CubeWeight(double, double,
double, double)
1. class Cube{ 22. class CubeInheritSuper{
2. protected double 23. public static void main(String[]
args) {
OOP Java is the easiest, scoring and my

height,width,depth; 24. CubeWeight cw1= new


favorite subject

3. Cube(double h,double w,double d)


{ CubeWeight(10,10,10,20.5);
4. [Link]("Constructor: 25. CubeWeight cw2= new
5.
CUBE"); CubeWeight(100,100,100,200.5);
6. height=h; 26. [Link]("[Link]()="+[Link]
me());
7. width=w;
27. [Link]("[Link]="+[Link]
8.
9. }
depth=d;
); CubeInheritSup
Outp
28. [Link]("[Link]()="+[Link]
10. double volume(){ me()); ut
Constructor:CUBE
[Link]
11.
[Link] return
CubeWeight extends Cube{ 29. [Link]("[Link]="+[Link]
[Link]*width*depth;
double weigth; ); Constructor:CUBEWEIG
12.
16. }
CubeWeight(double h,double
30.w,double
} d, TH
13.}
double m){ 31. } Constructor:CUBE
17. super(h,w,d); //call Constructor:CUBEWEIG
TH
superclassConstructor [Link]()=1000.0
18. [Link]=20.5
Using super to Call Superclass
[Link]("Constructor:CUBEWEIGTH");
Using super to access members
🞂 The second form of super acts somewhat like this, except that it
OOP Java is the easiest, scoring and my
favorite subject

always refers to the superclass of the subclass in which it is


used. member can be
🞂 Syntax: either a method or
[Link] an instance
variable.

🞂 This second form of super is most applicable to situations in


which member names of a subclass hide members by the same
name in the superclass.
Using super to access members: [Link]
1. class A{ [Link] SuperMemberDemo{
2. int 16. public static void
OOP Java is the easiest, scoring and my
favorite subject

3. } i; main(String[]
args)
4. class B extends A{ 17. {
5. int i,k; 18. B b= new B(12,56);
6. B(int a,int b){ 19. [Link]();
7. super.i=a 20. }
8. ; this.i=b; 21.}
9. }
10. void show(){
11.
Outp
[Link]("super.i="+super.i); ut
12. super.i=12
[Link]("this.i="+this.i); this.i=56
13. }
Using super to access members: [Link]
1. class A{ [Link] SuperMemberDemo{
2. int i=33; 20. public static void
OOP Java is the easiest, scoring and my
favorite subject
3. void show(){ main(String[]
4. [Link]("inside A:i="+i); args)
5. } 21. {
6. } 22. B b= new
B(12,56);
7. class B extends A{ 23. [Link]();
8. int i,k; 24. }
9. B(int a,int b){ 25.}
10. [Link]();
11. super.i=a;
12. this.i=b;
13. }
14. void show(){ Outp
15. [Link]("super.i="+super.i); ut
16. [Link]("this.i="+this.i); inside
17. } A:i=33
18.} super.i=12
B.i=56
Points to remember for super
🞂 When a subclass calls super( ), it is calling the constructor of its
OOP Java is the easiest, scoring and my
favorite subject

immediate superclass.
🞂 This is true even in a multileveled hierarchy.
🞂 super( ) must always be the first statement executed inside a
subclass constructor.
🞂 If a constructor does not explicitly call a superclass constructor,
the Java compiler automatically inserts a call to the no-
argument constructor of the superclass.
🞂 The most common application of super keyword is to eliminate
the ambiguity between members of superclass and sub class.
Why Inheritance
1. Reusability of code OOP Java is the easiest, scoring and my
favorite subject

2. To implement polymorphism at run time (method overriding).


Class A
Base Class

Class B
Derived Class
OOP Java is the easiest, scoring and my
favorite subject

Access Control
Access Control
Access Description
Modifier
OOP Java is the easiest, scoring and my
favorite subject

Private(-) The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
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.
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.
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 Control
Access Same Class Same Sub Class
OOP Java is the easiest, scoring and my
favorite subject Universal
Modifier Package
Private

Default

Protected

Public
Exercise
1. Why multiple and Hybrid inheritance is not supported in java.
OOP Java is the easiest, scoring and my
favorite subject

2. Implement inheritance in java using following diagram.


Shape
#String name
+ String color
Shape()

Circle Rectangle Triangle


~ radius: double ~height: double ~length: double
~PI: double ~width: double ~width: double
calCircleArea(): double calRectArea(): double calTriArea(): double
Interview Questions
1. Which class in Java is superclass of every other class?
OOP Java is the easiest, scoring and my
favorite subject

2. Can a class extend itself?


3. Can we assign superclass to subclass?
4. Can a class extend more than one class?
OOP Java is the easiest, scoring and my
favorite subject

Abstraction
Abstraction

🞂 Data abstraction is also termed as information hiding.


🞂 Abstraction is the concept of object-oriented programming that “represents” onlyandessential
OOP Java is the easiest, scoring
favorite subject
my attributes and “hides” unnecessary
information.
🞂 Abstraction is all about representing the simplified view and avoid complexity of the system.
🞂 It only shows the data which is relevant to the user.
🞂 In object-oriented programming, it can be implemented using Abstract Class.
Advantage:
🞂 It reduces programming complexity.
Example:
🞂 A car is viewed as a car rather than its numerous individual components.
Abstraction

OOP Java is the easiest, scoring and my


favorite subject
Abstraction vs. Encapsulation

Abstraction Encapsulation
It means act of removing/ It is act of binding code and
OOP Java is the easiest, scoring and my
favorite subject

withdrawing something data together and keep the


unnecessary. data secure from outside
Applied at Designing stage. interference.
Applied at Implementation
E.g. Interface and Abstract stage.
E.g. Access Modifier
Class (public, protected, private)
Purpose: Reduce code Purpose: Data protection
complexity
OOP Java is the easiest, scoring and my
favorite subject

Implementing
Abstraction
OOP Java is the easiest, scoring and my
favorite subject

Abstract class
Abstract class

🞂 Abstraction is a process of hiding the implementation details from the user, only the functionality will be
OOP Java is the easiest, scoring and my
provided to the user. favorite subject

🞂 In other words, the user will have the information on what the object does instead of how the object will
do it.
🞂 Abstraction is achieved using Abstract classes and interfaces.
🞂 A class which contains the abstract keyword in its declaration is known as abstract class.
⮩ Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )
⮩ But, if a class has at least one abstract method, then the class must be declared abstract.
⮩ If a class is declared abstract, it cannot be instantiated.
⮩ To use an abstract class, we have to inherit it to another class and provide implementations of the abstract
methods in it.
Abstract class (Example)

1. abstract class Car {


2. public abstract double getAverage();
OOP Java is the easiest, scoring and my

3. } favorite subject

4. class Swift extends Car{


5. public double getAverage(){
6. return 22.5;
7. }
8. }
9. class Baleno extends Car{
10. public double getAverage(){
11. return 23.2;
12. }
13.}
[Link] class MyAbstractDemo{
15. public static void main(String ar[]){ Outp
16. Swift s = new Swift(); ut
17. Baleno b = new Baleno(); 22.5
18. 23.2
[Link]([Link]());
19.
[Link]([Link]());
Why Abstract Class?

🞂 Sometimes, we need to define a superclass that declares the structure of a given abstraction without
OOP Java is the easiest, scoring and my
providing a complete implementation. favorite subject

🞂 The superclass will only define a generalized form, that will be shared by all the subclasses.
🞂 The subclasses will fill the details of every method.
🞂 When a superclass is unable to create a meaningful implementation for a method.
Points to remember for Abstract Class

🞂 To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the
OOP Java is the easiest, scoring and my
beginning of the class declaration. favorite subject

🞂 There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated
with the new operator. Such objects would be useless, because an abstract class is not fully defined.
🞂 Cannot declare abstract constructors, or abstract static methods.
🞂 Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or
be itself declared abstract.
OOP Java is the easiest, scoring and my
favorite subject

Interface
Interface

🞂 An interface is similar to an abstract class with the following exceptions


OOP Java is the easiest, scoring and my

⮩ All methods defined in an interface are abstract. favorite subject

⮩ Interfaces doesn’t contain any logical implementation


⮩ Interfaces cannot contain instance variables. However, they can contain public static final variables (ie.
constant class variables)
🞂 Interfaces are declared using the "interface" keyword
🞂 Interfaces are more abstract than abstract classes
🞂 Interfaces are implemented by classes using the "implements" keyword
🞂 Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are
declared without any body.
Interface:Syntax

public or not
used(default)
Methods are without body(no
OOP Java is the easiest, scoring and my

access interface name favorite subject

implementation) and all methods are


{ implicitly abstract.
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
implicitly final and static,
type final-varname1 = value; cannot be changed by the
type final-varname2 = value; implementing class, must
be initialized with a constant
// ... value.
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Implementing Interfaces

🞂 Once an interface has been defined, one or more classesOOP


can implement that interface.
Java is the easiest, scoring and my
favorite subject
🞂 To implement an interface, include the implements clause in a class definition, and then create the
methods defined by that interface.

access interface name


{
return-type method-name1(parameter-list);
type final-varname1 = value;
}

access class classname


[extends superclass]
[implements interface
[,interface...]] {
// class-body
}
Interface (Example)

interface VehicleInterface { class CarClass implements


OOP Java is the easiest, scoring and my
favorite subject

int a = 10; VehicleInterface


public void turnLeft(); {
public void turnRight(); public void turnLeft() {
public void accelerate();
public void slowDown(); [Link]("Left");
} }
We have to public void turnRight() {
Variable inHere access
public class DemoInterface{ provide
interface
public static are main(String[]
void by
specifier of
implementation [Link]("Right");
a) defaultmethod must be
to all the }
{ public, static, public
methods of the public void accelerate() {
CarClass cfinal
= new CarClass();
interface
[Link](); [Link]("Speed");
} }
} Outp
public void slowDown()
ut
{
Left
[Link](“Brake");
}
}
Interface (Example)

interface VehicleInterface { class CarClass implements


OOP Java is the easiest, scoring and my
favorite subject

int a = 10; VehicleInterface


public void turnLeft(); {
public void turnRight(); public void turnLeft() {
public void accelerate();
public void slowDown(); [Link]("Left");
} }
public void turnRight() {
public class DemoInterface{
public static void main(String[] [Link]("Right");
a) }
{
VehicleInterfa
CarClass public void accelerate() {
ce c = new CarClass();
[Link](); [Link]("Speed");
} }
}
variable c is declared to be of the interface type public void slowDown()
Outp {
VehicleInterface, yet it was ut
assigned an instance of CarClass. Left
[Link](“Brake");
}
}
Interface: Partial Implementations

🞂 If a class includes an interface but does not fully implement the methods defined by that interface, then
OOP Java is the easiest, scoring and my
that class must be declared as abstract. favorite subject

interface VehicleInterface { abstrac class CarClass implements


int a = 10; t VehicleInterface
public void turnLeft(); {
public void turnRight(); public void turnLeft() {
public void accelerate();
public void slowDown(); [Link]("Left");
} }
public void turnRight() {
public class DemoInterface{
Either class
public need to accelerate()
void implement all {the
public static void main(String[] [Link]("Right");
methods of Interface or declare that class
[Link]("Speed");
a) }
{ as abstract
} if partial implementation is
CarClass c = new CarClass(); required.
public void slowDown() {
[Link](); [Link](“Brake");
} }
}
Interface:Example
1. class
2.
CreateStack implements StackIntf{
int mystack[];
1. interface StackIntf{ 3. int tos;
OOP Java is the easiest, scoring and my
2. public void 4. CreateStack(int size){
favorite subject

push(int p); 5. mystack= new int[size];


3. public int pop(); 6. tos=-1;
4. }
7. }
8. public void push(int p){
9. if(tos==[Link]-1){
10.
[Link]("StackOverflow");
11. }
12. else{
13. mystack[++tos]=p;
14. }
15. }
16. public int pop(){
17. if(tos<0){
18.
[Link]("StackUnderflow");
19. return 0;
20. }
StackDem 21. else return mystack[tos--];
[Link]
Interface:Example [Link]
1. class StackDemo{ OOP Java is the easiest, scoring and my
favorite subject
2. public static void main(String[] args) {
3. CreateStack cs1= new CreateStack(5);
4. CreateStack cs2= new CreateStack(8);
5. for(int i=0;i<5;i++)
6. [Link](i);
7. for(int i=0;i<8;i++)
8. [Link](i);

9. [Link]("MyStack1=");
10. for(int i=0;i<5;i++)
11. [Link]([Link]());

12. [Link]("MyStack2=");

13. for(int i=0;i<8;i++)


14. [Link]([Link]());
15. }
16.}
Interfaces Can Be Extended

🞂 One interface can inherit another by use of the keyword OOP


extends.
Java is the easiest, scoring and my
favorite subject
🞂 The syntax is the same as for inheriting classes.
🞂 When a class implements an interface that inherits another interface, it must provide implementations
for all methods defined within the interface inheritance chain.
InterfaceHierarc 1. class MyClass1 implements B{
2. public void method1(){
[Link]
1. interface A{ 3.
2. void method1();
OOP Java is the easiest, scoring and my
[Link]("insideMyClass1:method1()");
favorite subject

3. void method2(); 4. }
4. } 5. public void method2(){
5. interface B extends A{ 6. [Link]("inside
6. void method3(); MyClass1:method2()");
7. } 7. }
8. interface C extends A{ 8.
9. void method4(); 9. public void method3(){
10.} 10. [Link]("inside
1. class InterfaceHierarchy{ 1. MyClass1:method3()");
2. public static void main [Link] MyClass2
} implements C{
2. public void method1(){
3. (String[] 12.}
3. [Link]("inside
args) {
4. MyClass1 c1=new MyClass2:method1()");
MyClass1(); 4. }
5. MyClass2 c2=new 5. public void method2(){
MyClass2(); 6. [Link]("inside
6. c1.method1(); MyClass2:method2()");
7. c1.method2(); 7. }
8. c1.method3(); 8. public void method4(){
9. c2.method1(); 9. [Link]("inside
10. c2.method2(); MyClass2:method4()");
Interface: Points to Remember

🞂 Any number of classes can implement an interface. OOP Java is the easiest, scoring and my
favorite subject
🞂 One class can implement any number of interfaces.
🞂 To implement an interface, a class must create the complete set of methods defined by the interface.
However, each class is free to determine the details of its own implementation.
Abstract class vs. Interface

Abstract class Interface


Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
OOP Java is the easiest, scoring and my
favorite subject

Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.
Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
A Java abstract class can have class members Members of a Java interface are public by
like private, protected, etc. default.
OOP Java is the easiest, scoring and my
favorite subject

Packages
Package

🞂 A Package can be defined as a grouping of related types providing access protection and name space
OOP Java is the easiest, scoring and my
management. favorite subject

🞂 Programmers can define their own packages to bundle group of classes/interfaces, etc.
🞂 Packages are used in Java in order to
 prevent naming conflicts
 control access,
 make searching/locating of classes/interfaces easier.
🞂 It is a good practice to group related classes implemented so that a programmer can easily determine
that the classes, interfaces are related.
🞂 Built-in Packages
⮩ Provided by Java API, e.g.:
▪ [Link].*
▪ [Link].*
▪ [Link].*
🞂 User-Defined Packages
⮩ Created by developers to structure project components logically.
import keyword

🞂 import keyword is used to import built-in and user-defined packages into your java source file so that
OOP Java is the easiest, scoring and my
your class can refer to a class that is in another packagefavorite
by subject
directly using its name.
🞂 There are 3 different ways to refer to class/interface that is present in different package
⮩ import the class/interface you want to use.
⮩ import all the classes/interfaces from the package.
⮩ Using fully qualified name.
🞂 We can import a class/interface of other package using a import keyword at the first line of code.
🞂 Example :

import [Link];

public class DemoImport {


public static void main(String[] args)
{
Scanner s = new Scanner([Link]);
// Code
}
}
import (importing all class/interface)

🞂 We can import all the classes/interfaces of other package using a import keyword at the first line of code
OOP Java is the easiest, scoring and my
with the wildcard (*). favorite subject

🞂 Example :
import [Link].*;
public class DemoImport {
public static void main(String[] args)
{
Scanner s = new Scanner([Link]);
Date d = new Date();
// Code
}
}

🞂 It is possible to use classes from other packages without importing the class using fully qualified name
of the class.
🞂 Example :
[Link] s = new [Link]([Link]);
Static Import

🞂 The static import feature of Java 5 facilitate the java programmer to access any static member of a class
OOP Java is the easiest, scoring and my
directly. favorite subject

🞂 Advantage : Less coding is required if you have to access any static member of a class more frequently.
🞂 Disadvantage : If you overuse the static import feature, it makes the program unreadable and
unmaintainable.

import static [Link];


public class S2{
public static void main(String args[]){
[Link]("Hello main");
}
} We need not to write
[Link] as we
have imported the out
statically
Creating a package

🞂 To create a package you need to write package statement followed by the name of the package.
OOP Java is the easiest, scoring and my
favorite subject
🞂 Syntax : package package_name;
🞂 Example :

package DS_student;

class Student {
// code
}
🞂 The package statement should be the first line in the source file.
🞂 There can be only one package statement in each source file, and it applies to all types in the file.
🞂 If a package statement is not used then the class/interfaces will be put into an unnamed package.
Package (Example)

package myPackage;
public class Animal { OOP Java is the easiest, scoring and my
favorite subject

public String name;


public void eat(){
[Link]("Organic Food !!!!");
}
public static void main(String[] args){
Animal a = new Animal();
[Link]();
}
}
.
Represent the current
🞂 To compile directory
javac –d . [Link]
-d . creates directories based on the package name
🞂 To Run the class file
(e.g., myPackage/).
java [Link]
OOP Java is the easiest, scoring and my
favorite subject
Access Control

Modifier Sam Same Same Differ


OOP Java is the easiest, scoring and my
favorite subject
Differe
e Packa Packa ent nt
Clas ge ge Packa Packag
s Sub Non ge e
Class Sub Sub Non
Class Class Sub
Class
Private
Default
Protected
Public
OOP Java is the easiest, scoring and my
favorite subject

WRAPPER CLASS
What is Wrapper Class

• A Wrapper class is a class whose object wraps


or contains primitive data types.
• When we create an object to a wrapper class, it
contains a field and in this field, we can store
primitive data types.
• In other words, we can wrap a primitive value
into a wrapper class object.
Wrapper Classes for converting
simple types
Simple Type Wrapper Class
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
Converting Primitive Numbers to Object
Numbers, using Constructor Methods
Constructor Calling Conversion Action

Integer intobj = new Integer(i); // Primitive integer to Integer object

Float floatobj = new Float(f); // Primitive float to Float object

Double doubleobj = new Double(d); // Primitive double to Double object

Long longobj = new Long(l); // Primitive long to Long object


Cont.

int i = 5;
Integer intobj = new Integer(i);
Converting Object Number to Primitive
Numbers
Method Calling Conversion Action

int i = [Link](); //Object to primitive integer

Float f = [Link](); //Object to primitive long

Double d = [Link](); // Object to primitive double

Long l = [Link](); // Object to primitive double


Cont.

Integer intobj = new Integer(5) ;


int i = [Link]( );
Converting primitive Numbers to Strings,
using toString( ) method
Method Calling Conversion Action

str1 = [Link](i); //Primitive integer to string

str2 = [Link](f); // Primitive float to string

str3 = [Link](d); // Primitive double to string

str4 = [Link](l); // Primitive long to string


Cont.
int i = 5;
Integer intobj = new Integer(i); // conversion of primitive int into
// Integer class object

String str = new String( );


str = [Link](); // conversion of Integer into String

Or

int i = 5;
String str = new String();
str = [Link]();
Converting String Objects to Numeric Objects, using
the Static method ValueOf()

Method Calling Conversion Action

DoubleVal = [Link](str); // converts string to Double object

FloatVal = [Link](str); // converts string to Float object

IntVal = [Link](str); // converts string to Integer object

LongVal = [Link](str); // converts string to Long object


Converting Numeric String to Primitive Numbers,
using Parsing Methods

int i = [Link](str); // converts string to primitive


integer

long l = [Link](str) ; // converts string to primitive


long

These methods throw a NumberFormatException if


the value of the str does not represent an integer.
OOP Java is the easiest, scoring and my
favorite subject

Strings
Strings in Java
• Strings represent a sequence of characters.

• The easiest way to represent a sequence of characters in Java is by using a


character array.

• In Java, strings are class objects and implemented using two classes: String and
StringBuffer.

• Declaration of string object:


String fname = new String(“Anil”);

• We can also create and use arrays that contain strings, e.g:
String nameArray[ ] = new String[5];
Methods in String class
Method call Task performed
s2= [Link] Converts string s1 to all lowercase
s2 = [Link] Converts the string s1 to all Uppercase
s2 = [Link](‘x’, ‘y’); Replace all appearances of x with y
s2 = [Link](); Remove white spaces at the beginning and end of the
string s1
[Link](s2) Returns true if s1 is equal to s2
[Link](s2) Returns true is s1 = s2, ignoring the case of characters.

[Link]() Gives the length of s1


[Link](n) Gives nth character of s1
[Link](s2) Returns negative if s1 < s2, positive if s1 > s2, and zero
if s1 is equal to s2.
[Link](s2) Concatenates s1 and s2.
Method call Task performed
[Link](n) Gives substring starting from nth character

[Link](n, m) Gives substring starting from nth character up to m th (not


including mth)

[Link](p) Creates a string object of the parameter p (simple type or


object)
[Link]() Creates a string representation of the object p.

[Link](‘x’) Gives the position of the first occurrences of ‘x’ in the string
s1.

[Link](‘x’, n) Gives the position of ‘x’ that occurs after nth position in the
string s1

[Link](variable) Converts the parameter value of string representation


Example, String functions
class StringCheck
{
public static void main(String args[ ])
{
String s1 = new String("James");
String s2 = new String("Gosling");
[Link]("\n string s1 = "+ s1);
[Link]("\n string s2 =" + s2);

String s3 = [Link]();
[Link]("\n After converting string " + s1 + " into lower case, i.e. s3 = " + s3);
String s4 = [Link]();
[Link]("\n After converting string " + s3 + " into upper case, i.e. s4 = " + s4);

String s5 = [Link]('J', 'G');


[Link]("\n After replacing the character J of " + s1 + " with G: " + s5);

Boolean b = [Link](s2);
[Link]("\n strings " + s1 + " and " + s2 + " are equal: " + b);

String s11 = new String("dennis");


String s22 = new String("DENNIS");
boolean b11 = [Link](s22);
[Link]("\n strings " + s11 + " and " + s22 + " are equal: " + b11);
Cont.
boolean b22 = [Link](s22);
[Link]("\n After ignoring the case, strings " + s11 + " and " + s22 + " are equal: " + b22);
char c = [Link](4);
[Link]("\n The character at 4th position of " + s1 + " is: " + c );
int l = [Link]();
[Link]("\n The length of the string " + s1 + " is: " + l);

String s6 = [Link](s2);
[Link]("\nThe strings " +s1+ " and" +s2+ " after concatenation is:" + s6);
String s7 = [Link](3);
[Link]("\n The substring of " + s1 + " after 3rd position is: " + s7);

String s8 = [Link](2, 6);


[Link]("\n The substring of "+s2+" starting from 2nd postion to position”);
[Link](“\n\tless than 4th is: " + s8);
int i = [Link]('a');
[Link]("\n Index of 'a' in the string " + s1 + " is: " + i);
}
}
Output:
OOP Java is the easiest, scoring and my
favorite subject

String Buffer
StringBuffer class

• String class creates strings of fixed lengths.

• StringBuffer class on other hand creates strings of


flexible length that can be modified in terms of both
length and content.

• One can insert characters and substrings in the middle


of string, or append another string to the end.
Commonly used StringBuffer methods

Method call Task performed


[Link](n, ‘x’) Modifies the nth character of x

[Link](s2) Appends the string s2 to s1 at the end

[Link](n, s2) Inserts the string s2 at the position n of the string s1

[Link](n) Sets the length of the string s1 to n. if n<[Link]() s1 is


truncated. If n > [Link]() zeros are added to s1.

You might also like