oopu unit 2
oopu unit 2
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.
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
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:
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
} }
CONSTRUCTOR OVERLOADING
29
CONSTRUCTOR OVERLOADING
EXAMPLE
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
35
INNER CLASSES
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.)
38
class ProgrammerInterview {
System.out.println("Programmer Interview!");
class Websit_anonymous {
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.
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.
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.
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.
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.
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
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
Output:
In this, methods must have same While in this, methods must have same
5.
name and different signature. name and same signature.
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
17
WHY CREATE ABSTRACT
METHODS?
18
Following is an example of the abstract method.
19
Examples of Abstract class that has an abstract method
Output :
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
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
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%
}}
31
CREATING A MULTIPLE
INTERFACE
If a class implements a multiple interfaces, it should override all the
abstract methods declared in all the interfaces.
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.
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
- 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
import package.class;
import package.*;
• Implicit in all programs: import java.lang.*;
• package statement(s) must appear first
CREATING PACKAGES
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
• Example:
import myPackage.ClassA;
import myPackage.secondPackage
• All classes/packages from higher-level package can be imported
as follows:
import myPackage.*;
USING A PACKAGE
• 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
• 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