OOPS Unit 2
OOPS Unit 2
Working with Objects - Implementing Classes - Object Construction - Static Variables and Methods – Packages - Nested
Classes – Abstract Class - Interfaces – Static, Default and Private Methods – Local and Anonymous Classes – Inheritance
– Extending a class - Object: The Cosmic Superclass – Wrapper classes.
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be
physical or logical (tangible and intangible). The example of an intangible object is the banking system.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so
writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an
object is the instance(result) of a class.
A class is a group of objects which have common properties. It is a template or blueprint from which objects
are created. It is a logical entity. It can't be physical.
A variable which is created inside the class but outside the method is known as an instance variable. Instance variable
doesn't get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is
known as an instance variable.
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.
We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java
source file, it is a good idea to save the file name with the class name which has main() method.
//Output
null
Implementing Classes
1. By reference variable
2. By method
3. By constructor
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
// Output: 101 Sonoo
We can also create multiple objects and store information in it through reference variable.
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
Output:
101 Sonoo
102 Amit
n this example, we are creating the two objects of Student class and initializing the value to these objects by
invoking the insert Record method
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output:
111 Karan
222 Aryan
As you can see in the above figure, object gets the memory in heap memory area. The reference variable
refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer
to the objects allocated in memory.
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
Output:
Anonymous object:
An object which has no reference is known as an anonymous object. It can be used at the time of object
creation only.
Output: 55 45
Method in Java
A method is a block of code or collection of statements or a set of code grouped together to perform a certain task or
operation. It is used to achieve the reusability of code. We write a method once and use it many times.
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-type, name, and
arguments. It has six components that are known as method header
Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method
name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the method.
Public: The method is accessible by all classes when we use public specifier in our application.
Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined.
Protected: When we use protected access specifier, the method is accessible within the same package or subclasses in
a different package.
Default: When we do not use any access specifier in the method declaration, Java uses default access specifier by
default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection,
void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the
functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method name
must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains
the data type and variable name. If the method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within
the pair of curly braces.
Naming a Method:
Types of Method:
o Predefined Method
o User-defined Method
Predefined Method:
In Java, predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods. It is also known as the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point. Some pre-defined methods are length(),
equals(), compareTo(), sqrt(), etc.
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
Addition.java
Static Method:
A method that has static keyword is known as static method. In other words, a method that belongs to a class
rather than an instance of a class is known as a static method. We can also create a static method by using
the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It is invoked by using the class
name. The best example of a static method is the main() method.
Display.java
InstanceMethodExample.java
public class InstanceMethodExample
{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
} // The sum is 25
o Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor method.
We can easily identify it because the method is prefixed with the word get. It is also known as getters.
It returns the value of the private field. It is used to get the value of the private field.
Syntax
Demo.java
Factory method:
It is a method that returns an object to the class to which it belongs. All static methods are factory methods.
For example, NumberFormat obj = NumberFormat.getNumberInstance();
Method Overloading in Java:
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
By changing the data type
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM
calls main() method which receives string array as arguments only.
Constructors in Java
<class_name>(){}
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.
Java Parameterized Constructor:
The parameterized constructor is used to provide different values to distinct objects. However, you can provide the
same values also.
Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They
are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the
number of parameters in the list and their types.
Counter(){
count++;//incrementing value
System.out.println(count);
}
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object
first then call main() method that will lead the problem of extra memory allocation.
this keyword in Java:
• There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the current
object.
• If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
Let's understand the problem if we don't use this keyword by the example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
In the above example, parameters (formal arguments) and instance variables are same. o, we are using this keyword to
distinguish local variable and instance variable.
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
class TestThis3{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
//Output: 111 ankit 5000.0
112 sumit 6000.0
2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler
automatically adds this keyword while invoking the method.
Java Package
• A java package is a group of similar types of classes, interfaces and sub-packages.
• Package in java can be categorized in two form, built-in package and user-defined package.
• There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
• Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
If you are not using any IDE, you need to follow the syntax given below:
Syntax:
javac -d directory javafilename
The -d switch specifies the destination where to put the generated class file. You can use any directory name like
/home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory,
you can use . (dot).
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the
current folder.
There are three ways to access the package from outside the package.
import package.*;
import package.classname;
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current package.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg(); }
}
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to
import.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Sequence of the program must be package then import then class.
Subpackage in java:
Example:
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
Inheritance in Java:
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object.
o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class,
extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also
called a base class or a parent class.
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
There are two types of modifiers in Java: access modifiers and non-access modifiers. The access modifiers in Java
specifies the accessibility or scope of a field, method, constructor, or class.
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc.
Here, we are going to learn the access modifiers only.
1) Private:
The private access modifier is accessible only within the class.
In this example, we have created two classes A and Simple. A class contains private data member and private
method. We are accessing these private members from outside the class, so there is a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.
2) Default
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.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the
package.
3) Protected
• The protected access modifier is accessible within package and outside the package but through inheritance
only.
• The protected access modifier can be applied on the data member, method and constructor. It can't be applied
on the class.
• It provides more accessibility than the default modifer.
n 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.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Java Inner Classes (Nested Classes)
• Java inner class or nested class is a class that is declared inside the class or interface.
• We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable.
• Additionally, it can access all the members of the outer class, including private data members and methods.
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Types of Nested classes in Java:
A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-static data
members and methods. It can be accessed by outer class name.
2) It can access static data members of the outer class, including private.
3) The static nested class cannot access non-static (instance) data members or
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
In this example, you need to create the instance of static nested class because it has instance method msg(). But you
don't need to create the object of the Outer class because the nested class is static and static properties, methods, or
classes can be accessed without an object.
A non-static class that is created inside a class but outside a method is called member inner class. It is also
known as a regular inner class. It can be declared with access modifiers like public, default, private, and
protected.
Syntax:
class Outer{
//code
class Inner{
//code
}
}
Example:
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
} // The data is 30
Java Local inner class
A class i.e., created inside a method, is called local inner class in java. Local Inner Classes are the inner classes that are
defined inside a block. Generally, this block is a method body. Sometimes this block can be a for loop, or an if clause
Java anonymous inner class is an inner class without a name and for which only a single object is created. An
anonymous inner class can be useful when making an instance of an object with certain "extras" such as overloading
methods of a class or interface, without having to actually subclass a class.
interface Eatable{
void eat();
}
class TestAnnonymousInner1{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){System.out.println("nice fruits");}
};
e.eat();
}
}
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is
an important part of OOPs (Object Oriented programming system).
Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are
created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class,
or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class
or a parent class
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or
subclass.
Example:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output: Programmer salary is:40000.0
Bonus of programmer is:10000
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits
the Animal class, so there is the single inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
// barking...
eating...
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below,
BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
// weeping...
barking...
eating...
Q) Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the
same method and you call it from child class object, there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So
whether you have same method or different, there will be compile time error.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where
you type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-
abstract methods (method with the body).
A method which is declared as abstract and does not have implementation is known as an abstract method.
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is provided by
the Honda class.
//running safely
Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of the
implementation class is provided by the factory method.
Another example of Abstract class in java
File: TestBank.java
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
// Rate of Interest is: 7 %
Rate of Interest is: 8 %
An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method
body.
There are mainly three reasons to use interface. They are given below.
Syntax:
interface <interface_name>{
// by default.
File: TestInterface2.java
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());
}}
// ROI: 9.15
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");}
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of
ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its
implementation is provided by the implementation class. For example:
interface Printable{
void print();
}
interface Showable{
void print();
}