0% found this document useful (0 votes)
2 views93 pages

oopu unit 2

This document provides an overview of Object Oriented Programming concepts in Java, focusing on classes, objects, methods, and access modifiers. It explains the role of constructors, static variables, and the use of the 'this' keyword, along with examples of method and constructor overloading. Additionally, it discusses access levels for class members using private, default, protected, and public modifiers.

Uploaded by

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

oopu unit 2

This document provides an overview of Object Oriented Programming concepts in Java, focusing on classes, objects, methods, and access modifiers. It explains the role of constructors, static variables, and the use of the 'this' keyword, along with examples of method and constructor overloading. Additionally, it discusses access levels for class members using private, default, protected, and public modifiers.

Uploaded by

hetraj189
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

1010043231

Object Oriented Programming with UML


UNIT- 2 Classes, Objects and Methods and Object oriented
thinking

SEMESTER: IV
PREPARED BY: Ms. Juhi Gor
CLASSES, OBJECTS AND METHODS

2
Objects and Classes:
Objects in Java

If we consider the real-world, we can find many objects around us, public class Dog
cars, dogs, humans, etc. All these objects have a attributes and a {
String name;
behavior.
int age;
If we consider a dog, then its attributes are - name, color, weight and String color;
the behaviors are - barking, wagging the tail, running.
Software objects also have attributes and behavior. A software void barking()
object's attribute is stored in fields and behavior is shown via methods. {
}
void hungry()
Classes in Java {
}
A class is a blueprint from which individual objects are created. void sleeping()
A class can contain any of Local variables, Instance variables, Class variables {
A class can have any number of methods to access the value of various kinds }
of methods. }
In the above example, barking(), hungry() and sleeping() are methods.
A class is a template for creating objects
Constructors
Every class has a constructor.
Local variables −
A constructor in Java is a special method which have the
Variables defined inside methods, constructors or same name as the class.
blocks are called local variables. It is used to initialize objects.
Declared and initialized within the method and Constructors do not have a return type not even void.
destroyed when the method has completed. Constructors are invoked using the new operator when an
object is created.
Instance variables − Each time a new object is created, at least one constructor
will be invoked.
Instance variables are variables within a class but
If we do not explicitly write a constructor for a class, the Java
outside any method. compiler builds a default constructor for that class.
These variables are initialized when the class is  A class can have more than one constructor.
instantiated.
Instance variables can be accessed from inside any
public class Puppy
method, constructor or blocks of that particular class. {
public Puppy()
Class variables − {
}
Class variables are variables declared within a class, public Puppy(String name)
outside any method, with the static keyword. {
// parameterized constructor
}
}
Explanation of Previous Example
The main class contains the main method that creates
three objects.
The new operator is used to create an object from the
constructor:
new SimpleCircle() creates an object with radius 1 ,
new SimpleCircle(25) creates an object with radius 25
and new SimpleCircle(125) creates an object with radius
125.
These three objects (referenced by circle1, circle2, and
circle3) have different data but the same methods.
Therefore, you can compute their respective areas by
using the getArea() method.
The data fields can be accessed via the reference of the
object using circle1.radius, circle2.radius, and
circle3.radius, respectively.
The object can invoke its method via the reference of
the object using circle1.getArea(), circle2.getArea(), and
circle3.getArea(), respectively.
These three objects are independent.
You can put the two classes into one file, but only one class in the file can be a public class.
Furthermore, the public class must have the same name as the file name.
Therefore, the file name is TestSimpleCircle.java, since TestSimpleCircle is public.
Access Modifiers (Visibility Modifiers) in JAVA
Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors.

There are four types of Java access modifiers:

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 Modifier within class within package outside package by outside package
subclass only

Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
class A
{
private int data=40;
private void msg()
{ Private Access Modifiers
System.out.println("Hello java");
}
}
In this example, we have created
two classes A and Simple.
public class Simple A class contains private data
{ member and private method.
public static void main(String args[]) We are accessing these private
{
A obj=new A();
members from outside the class, so
System.out.println(obj.data); there is a compile-time error.
//Compile Time Error
obj.msg();
//Compile Time Error
}
}
Default Access Modifiers

If you don't use any modifier, it is treated


as default by default.
The default modifier is accessible only
within package.
It cannot be accessed from outside the
package. It provides more accessibility
than private. But, it is more restrictive than
protected, and public.
In this example, we have created two
packages pack and mypack.
We are accessing the A class from
outside its package, since A class is not
public, so it cannot be accessed from
outside the package.
Protected Access Modifiers

In this example, we have created the two


packages pack and mypack.
The A class of pack package is public, so can
be accessed from outside the package.
But msg method of this package is declared
as protected, so it can be accessed from
outside the class only through inheritance.
Public Access Modifiers

The public access modifier is accessible


everywhere. It has the widest scope among all
other modifiers.
Static variable
If you declare any variable as static, it is known as a static variable.
Instance variables, constants, and methods may all be labeled as static
static means that the variable, constant, or method belongs to the class.
 It is not necessary to instantiate an object to access a static variable, constant or Method.
A static variable belongs to the class as a whole, not just to one object.
There is only one copy of a static variable per class.
All the member functions of the class can read and change a static variable.
The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
The static variable gets memory only once in the class area at the time of class loading.
It makes your program memory efficient (i.e. it saves memory).
Example Output:

111 Karan ITS


222 Aryan ITS
D:\SOU\Kruti_Even_2021-2022\OOP_UML_4th sem_SOU\PPTs\Example>javac
TestStaticVariable.java

D:\SOU\Kruti_Even_2021-2022\OOP_UML_4th sem_SOU\PPTs\Example>java
TestStaticVariable
111 Karan ITS
222 Aryan ITS

D:\SOU\Kruti_Even_2021-2022\OOP_UML_4th sem_SOU\PPTs\Example>javac
TestStaticVariable.java

D:\SOU\Kruti_Even_2021-2022\OOP_UML_4th sem_SOU\PPTs\Example>java
TestStaticVariable
111 Karan BBDIT
222 Aryan BBDIT

D:\SOU\Kruti_Even_2021-2022\OOP_UML_4th sem_SOU\PPTs\Example>

16
Program of the counter without static variable Program of counter by static variable
Java static method
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
Output:

111 Karan BBDIT


222 Aryan BBDIT
333 Sonoo BBDIT
Classes from the Java Library

The Date Class


java.util.Date date = new java.util.Date();

toString() method to return the date and time as a string.


System.out.println(date.toString()); //

Output : Mon Dec 26 07:43:39 EST 2020

The Random Class


this keyword in java

In java, this is a reference variable that refers to the current object.
There can be a lot of usage of java this keyword.
 this can be used to refer current class instance variable.
 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.
this: to refer current class instance variable
Solution of the problem by using this keyword
Understand the problem if we don't use this keyword

In the above example, parameters (formal arguments) and instance variables


are same. So, we are using this keyword to distinguish local variable and
instance variable.
this: to invoke current class method
class A
{
void display2()
{
System.out.println("hello display-2");
} You may invoke the method of the current
class by using the this keyword.
void display() If you don't use the this keyword, compiler
{ automatically adds this keyword while
System.out.println("hello display"); invoking the method.
//display2(); //same as this.display2()
this.display2();
}
}
class TestThis4
{
public static void main(String args[])
{
A a=new A();
a.display();
}
}
Passing objects to methods

When we pass a primitive type to a method, it is


passed by value. But when we pass an object to a
method, the situation changes dramatically, because
objects are passed by what is effectively call-by-
reference.
While creating a variable of a class type, we only
create a reference to an object. Thus, when we pass this
reference to a method, the parameter that receives it
will refer to the same object as that referred to by the
argument.
This effectively means that objects act as if they are
passed to methods by use of call-by-reference.
Array of Objects in Java
CONSTRUCTORS

Java has a mechanism, known as constructor, for automatically


initializing the values for an object, as soon as the object is
created.
Constructors have the same name as the class it resides in and
is syntactically similar to a method.
It is automatically called immediatey after the object for the
class is created by new operator.
Contructors have no return type, not even void, as the implicit
return type of a class’ constructor is the class type itself.
Types of Constructors: Implicit/Default, Explicit, Parameterized 26
EXPLICIT CONSTRUCTOR EXAMPLE
class Room{
double length, breadth, height, volume;
Room( ) { OUTPUT:
length = 14;
breadth = 12; The volume of the room is 1680
height = 10; } The volume of the room is 1680
double volComp( ) {
volume = length * breadth * height;
return volume; }
public static void main (String args[ ]) {
Room r1 = new Room();
Room r2 = new Room();
System.out.println("The volume of the room is "+r1.volComp(
));
System.out.println("The volume of the room is "+r2.volComp(
));
27
}
PARAMETERIZED CONSTRUCTOR EXAMPLE
class Room2{
double length, breadth, height, volume;
Room2( double l, double b, double h) {
length = l;
breadth = b; OUTPUT:
height = h; }
The volume of the room is 1680
// Computation of volume of the room
The volume of the room is 2640
double volComp( ) {
volume = length * breadth * height;
return volume; }
public static void main (String args[ ]) {
Room2 r1 = new Room2(14, 12, 10 );
Room2 r2 = new Room2(16, 15, 11 );
System.out.println("The volume of the room is
"+r1.volComp( ));
System.out.println("The volume of the room is
"+r2.volComp( )); 28

} }
CONSTRUCTOR OVERLOADING

• Constructors for a class have the same name as the


class but they can have different signature i.e.
different types of arguments or different number of
arguments. Such constructors can be termed as
overloaded constructors.
• In the example given on next slide, we have two
different classes, Rectangle and ConstOverloading.
Rectangle class has two constructors, both with
same names but different signatures. Second class
ConstOverloading, has the main( ) method inside it.

29
CONSTRUCTOR OVERLOADING
EXAMPLE

class Rectangle{ class ConstOverloading {


int l, b;
Rectangle(){
public static void main(String args[]) {
l = 10; Rectangle rectangle1=new Rectangle();
b = 20; System.out.println("The area of a rectangle using first
} constructor is: "+rectangle1.area());
Rectangle(int x, int y){ Rectangle rectangle2=new Rectangle(4,5);
l = x;
b = y; System.out.println("The area of a rectangle using
}
second constructor is: "+rectangle2.area();
int area() { }}
return l*b;
}} OUTPUT:
The area of a rectangle using first constructor is: 200
The area of a rectangle using second constructor is: 20 30
METHOD OVERLOADING

• In method overloading two methods can have the


same name but different signature i.e. different
number or type of parameters.
• The concept is advantageous where same kind of
activities are to be performed but with different
input parameters

31
class OverloadDemo {
void test() {
System.out.println("No parameters"); }
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a); } D:\SOU\Kruti_Even_2021-2022\OOP_UML_4th
// Overload test for two integer parameters. sem_SOU\PPTs\Example>java MethodOverload
void test(int a, int b) {
No parameters
a: 10
System.out.println("a and b: " + a + " " + b); }
a and b: 10 20
// overload test for a double parameter
double a: 123.2
double test(double a) {
Result of ob.test(123.2): 15178.240000000002
System.out.println("double a: " + a);
return a*a; }}
class MethodOverload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
//result = ob.test(123.2);
32
System.out.println("Result of ob.test(123.2): " + ob.test(123.2));
}}
final keyword
The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final keyword can be used with variable, method and class

1) Java final variable 2) Java final class


If you make any variable as final, you cannot If you make any class as final, you cannot
change the value of final variable(It will be extend it.
constant).

Output: Compile Time Error Output: Compile Time Error


3) Java final method
If you make any method as final, you cannot override it.

Output: Compile Time Error


CLEANING UP UNUSED OBJECT

• Java allows a programmer to create as many objects as


he/she wants but frees him/her from worrying about
destroying them. The Java runtime environment deletes
objects when it determines that they are no longer required.
• The Java runtime environment has a garbage collector that
periodically frees the memory used by objects that are no
longer needed.
• Before an object gets garbage collected, the garbage collector
gives the object an opportunity to clean up itself through a call
to the object's finalize() method. This process is known as
finalization.

35
INNER CLASSES

• An inner class can be defined and instantiated all inside a


class, or even within an expression.
• Nested classes:-It is possible to define a class within another class
Scope:- bounded by the scope of its enclosing class.
Two types of nested class
• Static class: static modifier, it must access the member of its
enclosing class through object (less use)
• Non static class(Inner class):It has access to all variables
and methods of its outer class and may refer to them
directly.

36
class outer
{
int outer_x=100;
void test(){
Inner inner=new Inner();
inner.display();
}
//this is inner class

class Inner{
void display()
OUTPUT:
{
D:\>javac InnerclassDemo.java
System.out.println(display:outer_x="+outer_x);
}
D:\>java InnerclassDemo
}
display:outer_x=100
}
class InnerclassDemo{
public static void main(string args[])
{
Outer outer=new outer();
outer.test();
}
} 37
INNER CLASSES (CONTD.)

• Anonymous Inner classes


• An anonymous inner class is one that is not assigned a
name.
• Such classes are created on the fly i.e. they are created,
instantiated, used and garbage collected when they are
done.
• They are automatically assigned a name as
Outerclassname$1.
• This anonymity helps in eliminating the unnecessary named
objects. Besides, it makes the program more readable.

38
class ProgrammerInterview {

public void read() {

System.out.println("Programmer Interview!");

class Websit_anonymous {

/* This creates an anonymous inner class: */

public static void main(String args[]){

ProgrammerInterview pInstance = new ProgrammerInterview()

public void read() {

System.out.println("anonymous ProgrammerInterview");

};

OUTPUT:

D:\>javac Websit_anonymous.java

D:\>java Websit_anonymous

anonymous ProgrammerInterview
RECURSION
• Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called
recursive method.
• It makes the code compact but complex to understand.
public class RecursionExample3 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}
}
OUTPUT:
D:\>java RecursionExample
Factorial of 5 is: 120
OBJECT ORIENTED THINKING

1
Abstraction Encapsulation
Abstraction is a feature of OOPs that hides Encapsulation is also a feature of OOPs. It hides the
the unnecessary detail but shows the essential code and data into a single entity or unit so that the
information. data can be protected from the outside world.
It solves an issue at the design level. Encapsulation solves an issue at implementation level.

It can be implemented using abstract It can be implemented by using the access


classes and interfaces. modifiers (private, public, protected).

It is the process of gaining information. It is the process of containing the information.

In abstraction, we use abstract classes and interfaces to We use the getters and setters methods to hide the
hide the code complexities. data.

The objects are encapsulated that helps to perform The object need not to abstract that result in
abstraction. encapsulation.
Big integer and Big decimal class
The BigInteger and BigDecimal classes can be used to represent integers or decimal numbers of any size and precision.
If you need to compute with very large integers or high-precision floating-point values, you can use the BigInteger and
BigDecimal classes in the java.math package.

You can use new BigInteger(String) and new BigDecimal(String) to create an instance of BigInteger and BigDecimal,
use the add, subtract, multiply, divide, and remainder methods to perform arithmetic operations, and use the
compareTo method to compare two big numbers.

For example, the following code creates two BigInteger objects and multiplies them.

BigInteger a = new BigInteger("9223372036854775807");


BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 * 2
System.out.println(c); // 18446744073709551614.

There is no limit to the precision of a BigDecimal object.

BigDecimal a = new BigDecimal(1.0);


BigDecimal b = new BigDecimal(3);
BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP);
System.out.println(c);
The output is 0.33333333333333333334.
Java Inheritance (Subclass and Super class)

In Java, it is possible to inherit attributes and methods from


one class to another.

Subclass (child) - the class that inherits from another class


Super class (parent) - the class being inherited from

To inherit from a class, use the extends keyword.


It is useful for code reusability.
Reuse attributes and methods of an existing class when you
create a new class.
Output :
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field
of own class as well as of Employee class i.e. code reusability.
Types of inheritance in
java`
Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which
is referred by super reference variable.

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.
1) super is used to refer immediate parent class instance variable.

 We can use super keyword to access the data member or field of parent class.
 It is used if parent class and child class have same fields.

In this example, Animal and Dog both classes have


a common property color.
If we print color property, it will print the color of
current class by default.
To access the parent property, we need to use
super keyword.

Output:

black
white
2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method.
It should be used if subclass contains the same method as parent class.
In other words, it is used if method is overridden.

In this example Animal and Dog both classes have eat()
method if we call eat() method from Dog class, it will call
the eat() method of Dog class by default because priority
is given to local.
To call the parent class method, we need to use super
keyword.

Output:

eating...
barking...
3 ) C O NS TR U CTO RS O F TH E S U P E R C L A S S .

class Constructor_A_Revised {
Constructor_A_Revised()
{
System.out.println(“Constructor A Revised”);
}}
class Constructor_B_Revised extends Constructor_A_Revised {
/*Constructor_B_Revised()
{
System.out.println(“Constructor B”); OUTPUT:
}*/
Constructor_B_Revised(int a) { Constructor A Revised
a++;
Constructor B Revised 12
System.out.println(“Constructor B Revised “+ a ); }}
Constructor C Revised
class Constructor_C_Revised extends Constructor_B_Revised
{
Constructor_C_Revised() {
super(11); // if omitted compile time error results
System.out.println(“Constructor C Revised”); }
public static void main (String args[]) {
Constructor_C_Revised a=new Constructor_C_Revised();
}}

9
Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

The method must have the same name as in the parent class
The method must have the same parameter as in the parent class.
There must be an IS-A relationship (inheritance).
Example of method overriding

In this example, we have defined the run method


in the subclass as defined in the parent class but it
has some specific implementation. T
he name and parameter of the method are the
same, and there is IS-A relationship between the
classes, so there is method overriding.

Output:

Bike is running safely


S.NO Method Overloading Method Overriding
Method overloading is a compile Method overriding is a run time
1.
time polymorphism. polymorphism.

While it is used to grant the specific


It help to rise the readability of the implementation of the method which is
2.
program. already provided by its parent class or
super class.

While it is performed in two classes


3. It is occur within the class.
with inheritance relationship.

Method overloading may or may While method overriding always needs


4.
not require inheritance. inheritance.

In this, methods must have same While in this, methods must have same
5.
name and different signature. name and same signature.

In method overloading, return


type can or can not be be same, While in this, return type must be
6.
but we must have to change the same or c
parameter. 12
Polymorphism in JAVA

The word polymorphism means having many forms.


Real life example of polymorphism: A person at the same time can have different characteristic. Like
a man at the same time is a father, a husband, an employee. So the same person posses different
behavior in different situations. This is called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented Programming.
Polymorphism allows us to perform a single action in different ways.
In other words, polymorphism allows you to define one interface and have multiple Implementations.

In Java polymorphism is mainly divided into two types:

(1)Compile time Polymorphism (static polymorphism)

 Method Overloading is the example of compile time polymorphism.


 Which method is to be called is determined by the arguments we pass while calling methods.
 This happens at compile time so this type of polymorphism is known as compile time
polymorphism.

13
(2)Runtime Polymorphism (dynamic polymorphism)
It is also known as Dynamic Method Dispatch.
Method Overriding is the example of Run time polymorphism.
Dynamic polymorphism is a process in which a call to an overridden method is resolved at runtime,
that's why it is called runtime polymorphism.
When an overridden method is called through a reference
class ABC
of parent class, then type of the object determines which
{
public void myMethod() method is to be executed. Thus, this determination is made
{ System.out.println("Overridden Method"); } at run time.
} Since both the classes, child class and parent class have
public class XYZ extends ABC the same method myMethod.
{
Which version of the method(child class or parent class)
public void myMethod()
{ System.out.println("Overriding Method"); } will be called is determined at runtime by JVM.
In the third case the method of child class is to be
public static void main(String args[]) executed because which method is to be executed is
{ determined by the type of object and since the object
ABC obj1 = new ABC();
belongs to the child class, the child class version of
obj1.myMethod();
XYZ obj2 = new XYZ(); myMethod() is called.
obj2.myMethod();
ABC obj3 = new XYZ(); Output :
obj3.myMethod(); Overridden Method
} Overriding Method 14
} Overriding Method
LATE BINDING VS EARLY BINDING

• Binding is connecting a method call to a


method body.
• When binding is performed before the
program is executed, it is called early
binding.
• If binding is delayed till runtime it is late
binding.
• Also known as dynamic binding or runtime
binding.
• All the methods in Java use late binding
(except static and final).
15
Abstract class in Java
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
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, you have to inherit it from another class, provide implementations to the
abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.

Abstract Method in Java


If you want a class to contain a particular method but you want the actual implementation of that
method to be determined by child classes, you can declare the method in the parent class as an
abstract.
abstract keyword is used to declare the method as abstract.
You have to place the abstract keyword before the method name in the method declaration.
An abstract method contains a method signature, but no method body.
Instead of curly braces, an abstract method will have a semicolon (;) at the end.
16
ABSTRACT CLASS

• Abstract classes are classes with a generic


concept, not related to a specific class.
• Abstract classes define partial behaviour and
leave the rest for the subclasses to provide.
• contain one or more abstract methods.
• abstract method contains no implementation,
i.e. no body.
• Abstract classes cannot be instantiated, but
they can have reference variable.
• If the subclasses does not override the abstract
methods of the abstract class, then it is
mandatory for the subclasses to tag itself as
abstract.

17
WHY CREATE ABSTRACT
METHODS?

• to force same name and signature pattern in


all the subclasses
• subclasses should not use their own naming
patterns
• They should have the flexibility to code these
methods with their own specific
requirements.

18
Following is an example of the abstract method.

Declaring a method as abstract has two consequences


The class containing it must be declared as abstract.
Any class inheriting the current class must either override the abstract method or declare itself
as abstract.
Suppose Salary class inherits the Employee class, then it should implement computePay()

19
Examples of Abstract class that has an abstract method

Output :

Rate of Interest is: 7 %


Rate of Interest is: 8 %

Output :

running safely
20
EXAMPLE OF ABSTRACT CLASS
abstract class Animal
{ class Dog extends Animal
{
String name; Dog(){
String species; super("Dog","puppy");
}
Animal(String n, String s) void sound()
{
{ System.out.println("Dog Bow ! Bow !");
name=n; }
}
species=s;
} class Demo_Abstract{
void eat(String fooditem)
public static void main(String args[])
{ {
System.out.println(species +" "+ name + "likes to have "+ Lion l = new Lion();
fooditem); l.eat("flesh");
l.sound();
}
abstract void sound(); Dog d = new Dog();
d.eat("biscuits");
} d.sound();
class Lion extends Animal }
{ D:\SOU\Kruti_Even_2021-2022\OOP_UML_4th
Lion(){ sem_SOU\PPTs\Example>javac Demo_Abstract.java
super("Lion", "Asiatication"); D:\SOU\Kruti_Even_2021-2022\OOP_UML_4th
}
sem_SOU\PPTs\Example>java Demo_Abstract
void sound()
{
System.out.println("Lions Roar ! Roar!"); Asiatication Lionlikes to have flesh
} Lions Roar ! Roar!
} puppy Doglikes to have biscuits 21
Dog Bow ! Bow !
WHAT IS AN INTERFACE?
An interface is a just like a class that contains only constants and abstract methods.
Cannot be instantiated (You Can not create object).
Only classes that implements interfaces can be instantiated.
One class can implement many interfaces
One interface can be implemented by many classes
By providing the interface keyword, Java allows you to fully utilize the "one interface, multiple
methods" aspect of polymorphism.
If a class implements an interface, it should override all the abstract methods declared in the
interface.
Why not just use abstract classes?
Java does not permit multiple inheritance from classes, but permits implementation of multiple
interfaces.
INTERFACES

Interfaces is a collection of methods which are public and abstract by


default.
The implementing objects have to inherit the interface and provide
implementation for all these methods.
multiple inheritance in Java is allowed through interfaces
Interfaces are declared with help of a keyword interface

23
SYNTAX FOR CREATING
INTERFACE
interface interfacename
{
returntype methodname(argumentlist);

}
The class can inherit interfaces using implements
keyword
– class classname implements interfacename{}

24
Interface Example: Bank
interface Bank
{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
INTERFACE
EXAMPLE
interface Calculator {
int add(int a,int b);
int subtract(int a,int b);
int multiply(int a,int b);
int divide(int a,int b);
}

26
EXAMPLE (CONTD.)
class Normal_Calculator implements Calculator
{
public int add(int a,int b){
return a+b;}
public int subtract(int a,int b){
return a-b;}
public int multiply(int a,int b){
return a*b;}
public int divide(int a,int b){
return a/b;}
public static void main(String args[]){
Normal_Calculator c=new Normal_Calculator();
System.out.println(“Value after addition = “+c.add(5,2));
System.out.println(“Value after Subtraction = “+c.subtract(5,2));
System.out.println(“Value after Multiplication = “+c.multiply(5,2));
System.out.println(“Value after division = “+c.divide(5,2)); }}

27
THE OUTPUT

Value after addition = 7


Value after Subtraction = 3
Value after Multiplication= 10
Value after division = 2

28
VARIABLES IN INTERFACE
• They are implicitly public, final, and static
• As they are final, they need to be assigned a
value compulsorily.
• Being static, they can be accessed directly
with the help of an interface name
• as they are public we can access them from
anywhere.

29
import java.util.Random; public static void main(String args[]) {
interface SharedConstants { Question q = new Question();
class Question implements SharedConstants { answer(q.ask());
int NO = 0; Random rand = new Random(); answer(q.ask());
int YES = 1; int ask() { answer(q.ask());
int prob = (int) (100 * rand.nextDouble()); answer(q.ask());
int MAYBE = 2; if (prob < 30) }
int LATER = 3; return NO; // 30% }
else if (prob < 60)
int SOON = 4; return YES; // 30%
int NEVER = 5; else if (prob < 75)
return LATER; // 15%
} else if (prob < 98)
return SOON; // 13%
else
return NEVER; // 2%
}}

class AskMe implements SharedConstants {


static void answer(int result) {
switch(result) {
case NO:
System.out.println("No");
break; OUTPUT:
case YES:
System.out.println("Yes"); D:\SOU\Var_int>javac *.java
break;
case MAYBE:
System.out.println("Maybe"); D:\SOU\Var_int>java AskMe
break; Soon
case LATER:
System.out.println("Later"); Later
break; Yes
case SOON:
System.out.println("Soon"); Soon
break;
case NEVER:
System.out.println("Never");
break;
} } 30
EXTENDING
INTERFACES
• One interface can inherit another interface
using the extends keyword and not the
implements keyword.
• For example,
interface A extends B { }

31
CREATING A MULTIPLE
INTERFACE
If a class implements a multiple interfaces, it should override all the
abstract methods declared in all the interfaces.

public Class ClassName implements InterfaceName1,


InterfaceName2, …, InterfaceNameN
{
methods1 implementation;
methods2 implementation;
...
methodsN implementation;
}
Multiple Inheritance
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[])


{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Important points about interface or summary of article:

 We can’t create instance(interface can’t be instantiated) of interface but we can make reference of it
that refers to the Object of its implementing class.
 Interface methods do not have a body - the body is provided by the "implement" class
 A class can implement more than one interface.
 If a class implements an interface, it should override all the abstract methods declared in the
interface.
 An interface can extends another interface or interfaces (more than one interface) .
 An interface can be a nested.
 Interface methods are by default public and abstract. And all the fields are public, static, and final.
 Interfaces are designed to support dynamic method resolution at run time.
 Interface variables must be initialized at the time of declaration otherwise compiler will throw an error.
 An interface cannot contain a constructor (as it cannot be used to create objects)
 Interface provides full abstraction as none of its methods have body. On the other hand abstract class
provides partial abstraction as it can have abstract and concrete(methods with body) methods both.
 It is used to achieve multiple inheritance.
 Variable names conflicts can be resolved by interface name.
Abstract class Interface
1) Abstract class can have abstract and non-abstract Interface can have only abstract methods.
methods.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and non- Interface has only static and final variables.
static variables.

4) Abstract class can provide the implementation of Interface can't provide the implementation of abstract
interface. class.
5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.

6) An abstract class can extend another Java class and An interface can extend another Java interface only.
implement multiple Java interfaces.

7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword "implements".

8) A Java abstract class can have class members like private, Members of a Java interface are public by default.
protected, etc.

Interface provides partial abstraction Interface provides full abstraction

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Instance of operator in JAVA

The java instanceof operator is used to test whether the object is an instance of the specified type
(class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the
instance with type.
It returns either true or false. An object of subclass type is also a type of
parent class.
For example, if Dog extends Animal then object
of Dog can be referred by either Dog or Animal
class.

Output: true

Output: true
PACKAGES

• Packages are Java’s way of grouping a number of related classes


and/or interfaces together into a single unit. That means,
packages act as “containers” for classes.
• The benefits of organising classes into packages are:
- The classes contained in the packages of other
programs/applications can be reused.
PACKAGES (CONT’D)

• - In packages classes can be unique compared with classes in


other packages. That two classes in two different packages can
have the same name. If there is a naming clash, then classes can
be accessed with their fully qualified name.
- Classes in packages can be hidden if we don’t want other
packages to access them.
- Packages also provide a way for separating “design” from coding.
JAVA FOUNDATION PACKAGES

Java provides a large number of classes groped into different


packages based on their functionality
• The six foundation Java packages are:
- java.lang :
Contains classes for primitive types, strings, math functions,
threads, and exception.
- java.util :
Contains classes such as vectors, hash tables, date etc.
- java.io :
Stream classes for I/O .
JAVA FOUNDATION PACKAGES
(CONT’D)

- java.awt :
Classes for implementing GUI – windows, buttons, menus etc.
- java.net :
Classes for networking .
- java.applet :
Classes for creating and implementing app.
USING SYSTEM PACKAGES

• The packages are organised in a hierarchical structure .For example, a package


named “java” contains the package “awt”, which in turn contains various classes
required for implementing GUI.Java
“java” Package containing
lang
“lang”, “awt”,.. packages;

awt Can also contain classes.

awt package containing classes.


graphics
font Classes containing methods
image
ACCESSING CLASSES FROM
PACKAGES

There are two ways of accessing the classes stored in packages:


• Using fully qualified class name
java.lang.Math.sqrt(x);
• Import package and use class name directly
import java.lang.Math
Matsqrt(x);
ACCESSING CLASSES FROM PACKAGES
(CONT’D)

• Selected or all classes in packages can be imported.

import package.class;
import package.*;
• Implicit in all programs: import java.lang.*;
• package statement(s) must appear first
CREATING PACKAGES

Java supports a keyword called “package” for creating user-


defined packages. The package statement must be the first
statement in a Java source file (except comments and white
spaces) followed by one or more classes.
package myPackage;
public class ClassA {
// class body
}
CREATING PACKAGES (CONT’D)

class ClassB {
}
Package name is “myPackage” and classes are considered as part
of this package; The code is saved in a file called “ClassA.java”
and located in a directory called “myPackage”.
ACCESSING A PACKAGE

• As indicated earlier, classes in packages can be accessed using a


fully qualified name or using a short-cut as long as we import a
corresponding package.
• The general form of importing package is:
import package1[.package2][…].classname
ACCESSING A PACKAGE (CONT’D)

• Example:
import myPackage.ClassA;
import myPackage.secondPackage
• All classes/packages from higher-level package can be imported
as follows:
import myPackage.*;
USING A PACKAGE

• Let us store the code listing below in a file named“ClassA.java” within


subdirectory named “myPackage”within the current directory (say “abc”).

• package myPackage;
• public class ClassA {
• // class body
• public void display()
• {
• System.out.println("Hello, I am ClassA");
• }
• }
• class ClassB {
• // class body
• }
USING A PACKAGE (CONT’D)

Within the current directory (“abc”) store the following code in a file
named“ClassX.java”
import myPackage.ClassA;
public class ClassX
{
public static void main(String args[])
{
ClassA objA = new ClassA();
objA.display();
}
}
COMPILING AND RUNNING

• en ClassX.java is compiled, the compiler compiles it and places


.class file in current directly. If .class of ClassA in subdirectory
“myPackage” is not found, it comples ClassA also.
• Note: It does not include code of ClassA into ClassX
• When the program ClassX is run, java loader looks for
ClassA.class file in a package called “myPackage” and loads it.
USING A PACKAGE

Let us store the code listing below in a file named“ClassA.java”


within subdirectory named“secondPackage” within the current
directory (say“abc”).

public class ClassC {


// class body
public void display()
{
System.out.println("Hello, I am ClassC");
}
}
USING A PACKAGE (CONT’D)

• Within the current directory (“abc”) store the following code in a file
named“ClassX.java”
import myPackage.ClassA;
import secondPackage.ClassC;
public class ClassY
{ public static void main(String args[]) {
ClassA objA = new ClassA();
ClassC objC = new ClassC();
objA.display();
objC.display();
}
}
OUTPUT

• Hello, I am ClassA
• Hello, I am ClassC

You might also like