Unit 2 Oops
Unit 2 Oops
Unit 2 Oops
For example:
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
Here, the func() method is overloaded. These methods have the same name but accept different
arguments.
Output:
Arguments: 1
Arguments: 1 and 4
Here, both overloaded methods accept one argument. However, one accepts the argument of type
int whereas other accepts String object.
OBJECTS AS PARAMETERS
A method can take an objects as a parameter. For example, in the following program, the
method setData( ) takes three parameter. The first parameter is an Data object. If you pass an
object as an argument to a method, the mechanism that applies is called pass-by-
reference, because a copy of the reference contained in the variable is transferred to the
method, not a copy of the object itself.
Example
class Data
{
int data1;
int data2;
}
class SetData {
Output
Data1:50
Data 2:100
JAVA METHOD RETURNING OBJECTS
A method can return any type of data, including class types that you create.
For example, in the following program, the changeObject() method returns an object in which
the value of a is ten greater than it is in the invoking object.
// Returning an object.
class Test
int a;
Test(int i) {
a = i;
}
Test changeObject() {
Test temp = new Test(a+10);
return temp;
}
}
ob2 = ob2.changeObject();
System.out.println("ob2.a after second increase: "
+ ob2.a);
}
}
OUTPUT
INHERITANCE
Inheritance is the mechanism in java by which one class is allow to inherit the features
(fields and methods) of another class. It is process of deriving a new class from an existing
class. A class that is inherited is called a superclass and the class that does the inheriting is
lationship. The keyword used for inheritance is extends.
Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
Here, the extends keyword indicates that we are creating a new class that derives from an
existing class.
Note: The constructors of the superclass are never inherited by the subclass
Advantages of Inheritance:
Code reusability - public methods of base class can be reused in derived classes
Data hiding – private data of base class cannot be altered by derived class
Overriding--With inheritance, we will be able to override the methods of the base
class in the derived class
Example:
// Create a superclass.
class BaseClass{
int a=10,b=20;
public void add(){
System.out.println(“Sum:”+(a+b));
// Create a subclass by extending class BaseClass.
public class Main extends BaseClass
{
public void sub(){
System.out.println(“Difference:”+(a-b));
}
public static void main(String[] args) {
Main obj=new Main();
/*The subclass has access to all public members of its superclass*/
obj.add();
obj.sub();
}
}
Sample Output:
Sum:30
Difference:-10
In this example, Main is the subclass and BaseClass is the superclass. Main object can
access the field of own class as well as of BaseClass class i.e. code reusability.
Types of inheritance
Single Inheritance :
In single inheritance, a subclass inherit the features of one superclass.
Example:
class Shape{
int a=10,b=20;
}
class Rectangle extends Shape{
public void rectArea(){
System.out.println(“Rectangle Area:”+(a*b));
public class Main
{
public static void main(String[] args) {
Rectangle obj=new Rectangle();
obj.rectArea();
}
}
ROHINI
Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class i.e. a derived class in turn acts as a base
class for another class.
Example:
class Numbers{
int a=10,b=20;
}
class Add2 extends Numbers{
int c=30;
public void sum2(){
System.out.println(“Sum of 2 nos.:”+(a+b));
}
}
class Add3 extends Add2{
public void sum3(){
System.out.println(“Sum of 3 nos.:”+(a+b+c));
}
}
public class Main
{
public static void main(String[] args) {
Add3 obj=new Add3();
obj.sum2();
obj.sum3();
}
}
Sample Output:
Sum of 2 nos.:30
Sum of 3 nos.:60
Hierarchical Inheritance:
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one sub class.
Example:
class Shape{
int a=10,b=20;
}
class Rectangle extends Shape{
public void rectArea(){
System.out.println(“Rectangle Area:”+(a*b));
}
}
class Triangle extends Shape{
public void triArea(){
System.out.println(“Triangle Area:”+(0.5*a*b));
}
}
public class Main
{
public static void main(String[] args) {
Rectangle obj=new Rectangle();
obj.rectArea();
Triangle obj1=new Triangle();
obj1.triArea();
}
}
Sample Output:
Rectangle Area:200
Triangle Area:100.0
Multiple inheritance
Java does not allow multiple inheritance:
To reduce the complexity and simplify the language
To avoid the ambiguity caused by multiple inheritance
For example, Consider a class C derived from two base classes A and B. Class C inherits
A and B features. If A and B have a method with same signature, there will be ambiguity to
call method of A or B class. It will result in compile time error.
class A{
void msg(){System.out.println(“Class A”);}
}
class B{
void msg(){System.out.println(“Class B “);}
}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Sample Output:
Compile time error
Direct implementation of multiple inheritance is not allowed in Java. But it is achievable
using Interfaces. The concept about interface is discussed in chapter.2.7.
Access Control in Inheritance
The following rules for inherited methods are enforced −
Variables declared public or protected in a superclass are inheritable in subclasses.
Variables or Methods declared private in a superclass are not inherited at all.
Methods declared public in a superclass also must be public in all subclasses.
Methods declared protected in a superclass must either be protected or public in
subclasses; they cannot be private.
Example:
// Create a superclass
class A{
int x; // default specifier
private int y; // private to A
Example:
class SuperCls
{
int x = 20;
}
/* sub class SubCls extending SuperCls */
class SubCls extends SuperCls
{
int x = 80;
void display()
{
System.out.println(“Super Class x: “ + super.x); //print x of super class
System.out.println(“Sub Class x: “ + x); //print x of subclass
}
}
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
SubCls obj = new SubCls();
obj.display();
}
}
Sample Output:
Super Class x: 20
Sub Class x: 80
In the above example, both base class and subclass have a member x. We could access x
of base class in sublcass using super keyword.
Use of super with methods:
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 (Method Overriding).
class SuperCls
{
int x = 20;
void display(){ //display() in super class
System.out.println(“Super Class x: “ + x);
}
}
/* sub class SubCls extending SuperCls */
class SubCls extends SuperCls
{
int x = 80;
void display() //display() redefined in sub class – method overriding
{
System.out.println(“Sub Class x: “ + x);
super.display(); // invoke super class display()
}
}
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
SubCls obj = new SubCls();
obj.display();
}
}
Sample Output:
Sub Class x: 80
Super Class x: 20
In the above example, if we only call method display() then, the display() of sub class gets
invoked. But with the use of super keyword, display() of superclass could also be invoked.
Use of super with constructors:
The super keyword can also be used to invoke the parent class constructor.
Syntax:
super();
super() if present, must always be the first statement executed inside a subclass
constructor.
When we invoke a super() statement from within a subclass constructor, we are
invoking the immediate super class constructor
Example:
class SuperCls
{
SuperCls(){
System.out.println(“In Super Constructor”);
}
}
/* sub class SubCls extending SuperCls */
class SubCls extends SuperCls
{
SubCls(){
super();
System.out.println(“In Sub Constructor”);
}
}
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
SubCls obj = new SubCls();
}
}
Sample Output:
In Super Constructor
In Sub Constructor
ORDER OF CONSTRUCTOR INVOCATION
Constructors are invoked in the order of their derivation
If a subclass constructor does not explicitly invoke a superclass constructor using
super() in the first line, the Java compiler automatically inserts a call to the no-
argument constructor of the superclass. If the superclass does not have a no-argument
constructor, it will generate a compile-time error.
Example:
class A
{
A(){
System.out.println(“A’s Constructor”);
}
}
/* sub class B extending A */
class B extends A
{
B(){
super();
System.out.println(“B’s Constructor”);
}
}
/* sub class C extending B */
class C extends B{
C(){
super();
System.out.println(“C’s Constructor”);
}
}
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
C obj = new C();
}
}
Sample Output:
A’s Constructor
B’s Constructor
C’s Constructor
Invoking Superclass Parameterized Constructor
To call parameterized constructor of superclass, we must use the super keyword as shown
below.
Syntax:
super(value);
Example:
class SuperCls{
int x;
SuperCls(int x){
this.x=x; // this refers to current invoking object
}
}
class SubCls extends SuperCls{
int y;
SubCls(int x,int y){
super(x); // invoking parameterized constructor of superclass
this.y=y;
}
public void display(){
System.out.println(“x: “+x+” y: “+y);
}
}
public class Main
{
public static void main(String[] args) {
SubCls obj=new SubCls(10,20);
obj.display();
}
}
Sample Output:
x: 10 y: 20
The program contains a superclass and a subclass, where the superclass contains a param-
eterized constructor which accepts a integer value, and we used the super keyword to invoke
the parameterized constructor of the superclass.
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.
In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation. The name and parameter of the method are the same,
and there is IS-A relationship between the classes, so there is method overriding.
There are many differences between method overloading and method overriding in java. A list
of differences between method overloading and method overriding are given below:
4) Method overloading is the example of compile time Method overriding is the example
polymorphism. of run time polymorphism.
5) In java, method overloading can't be performed by Return type must be same or
changing return type of the method only. Return covariant in method overriding.
type can be same or different in method
overloading. But you must have to change the
parameter.
Upcasting :
It is a technique in which a superclass reference variable refers to the object of the subclass.
Example :
Class Animal{ ]
Class Dog extends Animal{ }
Animal a=new Dog(); //upcasting
In the above example, we've created two classes, named Animal(superclass) &
Dog(subclass). While creating the object 'a', we've taken the reference variable of the
parent class(Animal), and the object created is of child class(Dog).
In the below code, we've created two classes: Phone & SmartPhone.
The Phone is the parent class and the SmartPhone is the child class.
The method on() of the parent class is overridden inside the child class.
Inside the main() method, we've created an object obj of the Smartphone() class by taking the
reference of the Phone() class.
When obj.on() will be executed, it will call the on() method of the SmartPhone() class
because the reference variable obj is pointing towards the object of class SmartPhone().
Program
class Phone{
public void showTime(){
System.out.println("Time is 8 am");
}
public void on(){
System.out.println("Turning on Phone...");
}
}
obj.showTime();
obj.on();
// obj.music(); Not Allowed
}
}
Output :
Time is 8 am
Turning on SmartPhone...
8. A class derived from the abstract class must implement all those methods that are
declared as abstract in the parent class.
9. If a child does not implement all the abstract methods of abstract parent class, then the
child class must need to be declared abstract as well.
Example 1
//abstract parent class
abstract class Animal
{
//abstract method
public abstract void sound();
}
//Lion class extends Animal class
public class Lion extends Animal
{
public void sound()
{
System.out.println(“Roars”);
}
public static void main(String args[])
{
Animal obj = new Lion();
obj.sound();
}
}
Output:
Roars
In the above code, Animal is an abstract class and Lion is a concrete class.
Example 2
abstract class Bank
{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class PNB extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
public class TestBank
{
public static void main(String args[])
{
Bank b=new SBI();//if object is PNB, method of PNB will be invoked
int interest=b.getRateOfInterest();
System.out.println(“Rate of Interest is: “+interest+” %”);
b=new PNB();
System.out.println(“Rate of Interest is: “+b.getRateOfInterest()+” %”);
}
}
Inheritance and Interfaces 2.19
Output:
Rate of Interest is: 7 %
Rate of Interest is: 8 %
Abstract class with concrete (normal) method
Abstract classes can also have normal methods with definitions, along with abstract
methods.
Sample Code:
abstract class A
{
abstract void callme();
public void normal()
{
System.out.println(“this is a normal (concrete) method.”);
}
}
public class B extends A
{
void callme()
{
System.out.println(“this is an callme (abstract) method.”);
}
public static void main(String[] args)
{
B b = new B();
b.callme();
b.normal();
}
}
Output:
this is an callme (abstract) method.
this is a normal (concrete) method.
Observations about abstract classes in Java
1. An instance of an abstract class cannot be created; But, we can have references
of abstract class type though.
Sample Code:
abstract class Base
{
abstract void fun();
}
class Derived extends Base
{
void fun()
{
System.out.println(“Derived fun() called”);
}
}
public class Main
{
public static void main(String args[])
{
// Base b = new Base(); Will lead to error
// We can have references of Base type.
Base b = new Derived();
b.fun();
}
}
Output:
Derived fun() called
2. An abstract class can contain constructors in Java. And a constructor of ab-
stract class is called when an instance of a inherited class is created.
Sample Code:
abstract class Base
{
Base()
{
System.out.println(“Within Base Constructor”);
}
abstract void fun();
}
class Derived extends Base
{
Derived()
{
System.out.println(“Within Derived Constructor”);
}
void fun()
{
System.out.println(“ Within Derived fun()”);
}
}
public class Main
{
public static void main(String args[])
{
Derived d = new Derived();
}
}
Output:
Within Base Constructor
Within Derived Constructor
3. We can have an abstract class without any abstract method. This allows us to create
classes that cannot be instantiated, but can only be inherited.
Sample Code:
abstract class Base
{
void fun()
{
System.out.println(“Within Base fun()”);
}
}
class Derived extends Base
{
}
public class Main
{
public static void main(String args[])
{
Derived d = new Derived();
d.fun();
}
}
Output:
Within Base fun()
4. Abstract classes can also have final methods (methods that cannot be
overridden).
Sample Code:
abstract class Base
{
final void fun()
{
System.out.println(“Within Derived fun()”);
}
}
class Derived extends Base
{
}
public class Main
{
public static void main(String args[])
{
Base b = new Derived();
b.fun();
}
}
Output:
Within Derived fun()
FINAL METHODS AND CLASSES
The final keyword in java is used to restrict the user. The java final keyword can be ap-
plied to:
variable
method
class
Java final variable - To prevent constant variables
Java final method - To prevent method overriding
Java final class - To prevent inheritance
Figure: Uses of final in java
{ {
OR
//code //code
} }
Sample Code:
final class XYZ
{
}
NESTED CLASSES
In Java, a class can have another class as its member. The class written within another
class is called the nested class, and the class that holds the inner class is called the outer
class.
Java inner class is defined inside the body of another class. Java inner class can be de-
clared private, public, protected, or with default access whereas an outer class can have only
public or default access. The syntax of nested class is shown below:
class Outer_Demo {
class Nested_Demo {
}
}
Types of Nested classes
There are two types of nested classes in java. They are non-static and static nested classes.
The non-static nested classes are also known as inner classes.
Non-static nested class (inner class)
○ Member inner class
○ Method Local inner class
○ Anonymous inner class
Static nested class
Type Description
Member Inner Class A class created within class and outside method.
Anonymous Inner Class A class created for implementing interface or extending class.
Its name is decided by the java compiler.
Method Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Nested Interface An interface created within class or interface.
JAVA PACKAGE
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.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
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).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
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.
Example of package that import the packagename.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
//save by B.java
1. package mypack;
2. import pack.*;
3.
4. class B{
5. public static void main(String args[]){
6. A obj = new A();
7. obj.msg();
8. }
9. }
OUTPUT:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
//save by B.java
1. package mypack;
2. import pack.A;
3.
4. class B{
5. public static void main(String args[]){
6. A obj = new A();
7. obj.msg();
8. }
9. }
OUTPUT:Hello
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when you
are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
OUTPUT:Hello subpackage