Aoop - Unit II
Aoop - Unit II
PROGRAMMING
Returning Objects, Recursion, Access Control, Static Members, Final Variables, Inner
Classes, Command Line Arguments, Variable Length Arguments.
Inheritance - Super Class, Sub Class, The Keyword super, protected Members, Calling
Order of Constructors
Method Overriding, the Object class, Abstract Classes and Methods, using final with
Inheritance.
DEFINING CLASSES IN JAVA
A class is a template for an object, and an object is an instance of a class. A class is declared by use of the class keyword.
Syntax:
class classname {
type instance-variable1;
type instance-variable2;
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodnameN(parameter-list) {
// body of method
}
• The data, or variables, defined within a class are called instance variables.
• The code is contained within methods.
• The methods and variables defined within a class are called members of the class.
• In most classes, the instance variables are acted upon and accessed by the methods defined for that class.
• Variables defined within a class are called instance variables because each instance of the class (that is, each object of
the class) contains its own copy of these variables.
• Thus, the data for one object is separate and unique from the data for another.
A Simple Class
class Box
{
double width;
double height;
double depth;
}
The new data type is called Box. This name is used to declare objects of type Box. The class declaration
only creates a template. It does not create an actual object.
class OverloadCons
METHODS
Syntax:
type name(parameter-list)
{
// body of method
}
• type specifies the type of data returned by the method. This can be any valid type, including class types
that you create.
• If the method does not return a value, its return type must be void.
• The name of the method is specified by name.
• The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are
essentially variables that receive the value of the arguments passed to the method when it is called. If the
method has no parameters, then the parameter list will be empty.
• Methods that have a return type other than void return a value to the calling routine using the following
form of the return statement:
Syntax: return value;
METHODS
// This program includes a method inside the box class.
class Box { mybox1.volume();
double width; mybox2.volume();
double height; }
double depth; }
Output:
void volume() { Volume is 3000.0
System.out.print("Volume is "); Volume is 162.0
System.out.println(width * height * depth);
} The first line here invokes the volume( ) method on mybox1.
} That is, it calls volume( ) relative to the mybox1 object, using the
class BoxDemo3 { object’s name followed by the dot operator.
public static void main(String args[]) {
Box mybox1 = new Box(); Thus, the call to mybox1.volume( ) displays the volume of the
Box mybox2 = new Box(); box defined by mybox1, and the call to mybox2.volume( )
displays the volume of the box defined by mybox2. Each time
mybox1.width = 10; volume( ) is invoked, it displays the volume for the specified
mybox1.height = 20; box.
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
Method- Returning a Value
Example: // get volume of first box
class Box { vol = mybox1.volume();
double width; System.out.println("Volume is " + vol);
double height;
double depth; // get volume of second box
double volume() vol = mybox2.volume();
{ System.out.println("Volume is " + vol);
return width * height * depth; }
} }
} Output:
class BoxDemo4 { Volume is 3000
public static void main(String args[]) Volume is 162
{
Box mybox1 = new Box();
Box mybox2 = new Box(); There are two important things to understand about returning
double vol; values:
• The type of data returned by a method must be compatible
mybox1.width = 10; with the return type specified by the method.
mybox1.height = 20; • The variable receiving the value returned by a method (such
mybox1.depth = 15; as vol, in this case) must also be compatible
with the return type specified for the method.
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
Method That Takes Parameters
{
Example: Box mybox1 = new Box();
// This program uses a parameterized method. Box mybox2 = new Box();
class Box { double vol;
double width; // initialize each box
double height; mybox1.setDim(10, 20, 15);
double depth; mybox2.setDim(3, 6, 9);
// get volume of first box
// compute and return volume
double volume() { vol = mybox1.volume();
return width * height * depth; System.out.println("Volume is " + vol);
} // get volume of second box
vol = mybox2.volume();
// sets dimensions of box System.out.println("Volume is " + vol);
void setDim(double w, double h, double d) { }
width = w; }
height = h; Output:
depth = d; Volume is 3000
} Volume is 162
}
class BoxDemo5 {
public static void main(String args[])
The this Keyword
• this keyword is used to to refer to the object that invoked it. Student stud1 = new Student(01,"Tarun");
• this can be used inside any method to refer to Student stud2 = new Student(02,"Barun");
the current object.
• this is always a reference to the object on which stud1.display();
the method was invoked. stud2.display();
• this() can be used to invoke current class constructor. }
}
Example:
class Student
{
int id;
String name; Output:
student(int id, String name) 01 Tarun
{ 02 Barun
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Overloading Methods
When two or more methods within the same class double test(double a) {
that have the same name, but their parameter declarations System.out.println("double a: " + a);
are different. The methods are said to be overloaded, and return a*a;
the process is referred to as method overloading. }
Method overloading is one of the ways }
that Java supports polymorphism. class Overload {
public static void main(String args[]) {
There are two ways to overload the method in java OverloadDemo ob = new OverloadDemo();
1. By changing number of arguments double result;
2. By changing the data type // call all versions of test()
ob.test();
Example: ob.test(10);
// Demonstrate method overloading. ob.test(10, 20);
class OverloadDemo { result = ob.test(123.25);
void test() { System.out.println("Result of ob.test(123.25): " + result);
System.out.println("No parameters"); }
} }
// Overload test for one integer parameter. Output:
void test(int a) { No parameters
System.out.println("a: " + a); 20
} a: 10
// Overload test for two integer parameters. a and b: 10 20
void test(int a, int b) { double a: 123.25
System.out.println("a and b: " + a + " " + b); Result of ob.test(123.25): 15190.5625
Passing and Returning Objects
Although Java is strictly passed by value, the precise effect differs between whether
a primitive type or a reference type is passed. 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.
Java does this interesting thing that’s sort of a hybrid between pass-by-value and
pass-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.
Changes to the object inside the method do reflect the object used as an argument.
Example
From the method side, a reference of type o with a name a is declared and it’s
initially assigned to null.
As we call the method equalTo, the reference ‘o’ will be assigned to the object which is
passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as the following statement execute.
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob2’. Since
values of ‘a’ and ‘b’ are same for both the references, so if(condition) is true, so boolean
true will be return.
• if(o.a == a && o.b == b)
• Again ‘o’ will reassign to ‘ob3’ as the following statement execute.
• System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
the equal To method is called on ‘ob1’ , and ‘o’ is referring to ‘ob3’. Since values
of ‘a’ and ‘b’ are not the same for both the references, so if(condition) is false, so
else block will execute, and false will be returned.
// Java Program to Demonstrate Objects Passing to Methods.
// Class
// Helper class
class ObjectPassDemo {
int a, b;
// Constructor
ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}
// Method
boolean equalTo(ObjectPassDemo o)
{
// Returns true if o is equal to the invoking
// object notice an object is passed as an
// argument to method
return (o.a == a && o.b == b);
}}
// Main class
public class GFG {
// Main driver method
public static void main(String args[])
{
// Creating object of above class inside main()
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
Output:
ob1 == ob2: true ob1 == ob3: false
Returning Objects
• In java, a method can return any type of data, including objects. For example, in the following program,
the incrByTen( ) method returns an object in which the value of an (an integer variable) is ten greater than it is in the
invoking object.
• // Java Program to Demonstrate Returning of Objects
// Class 1
class ObjectReturnDemo {
int a;
// Constructor
ObjectReturnDemo(int i) { a = i; }
int fact(int n) {
GFG f = new GFG();
{
System.out.println("Factorial of 3 is “+ f.fact(3));
int result;
System.out.println("Factorial of 4 is “+ f.fact(4));
if (n == 1)
System.out.println("Factorial of 5 is “+ f.fact(5));
return 1;
}
result = fact(n - 1) * n;
}
return result;
}
} Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120
//
Direct or Indirect recursion
• A function fun is called direct recursive if it calls the same function fun. A function fun is called
indirect recursive if it calls another function say fun_new and fun_new calls fun directly or
indirectly.
• i) . Direct recursion:
• void directRecFun()
• { // Some code.... directRecFun();
• // Some code... }
• Ii) Indirect recursion:
• void indirectRecFun1()
• { // Some code... indirectRecFun2(); // Some code... }
• void indirectRecFun2()
• { // Some code... indirectRecFun1(); // Some code... }
Access Control
Access Control in Java refers to the mechanism used to restrict or allow access to
certain parts of a Java program, such as classes, methods, and variables.
Access control determines which classes and objects can access specific codes or data
within a program.
Access Control Modifiers in Java
Access control modifiers in Java are keywords that can be used to control access to classes, fields,
and methods.
Access control modifiers determine the level of access that other classes or objects have to a
particular class, field, or method.
The private access control modifier in Java is used to restrict access to a class member to only
within the same class.
This means that a private member cannot be accessed from outside of the class, including from
any subclass of the class.
This helps to promote encapsulation and information hiding in the class.
The syntax for using the private access control modifier in Java is as follows:
Explanation: In the above code snippet, we have declared a private instance variable called
myPrivateVar and a private method called myPrivateMethod().
These members can only be accessed from within the same class.
2. Default Access Control Modifier in Java
The default or package-private access control modifier in Java is used when no access modifier is
specified.
It makes the class member accessible only within the same package. This means that a default
member cannot be accessed from outside of the package, including from any subclass of the class,
if it is defined in a different package.
The syntax for using the default access control modifier in Java is as follows:
• In Java, static members are those which belongs to the class and you can access these
members without instantiating the class.
• The static keyword can be used with methods, fields, classes (inner/nested), blocks.
• Static Methods − You can create a static method by using the keyword static. Static
methods can access only static fields, methods. To access static methods there is no need
to instantiate the class, you can do it just using the class name as −
public class MyClass
{
public static void sample()
{
System.out.println("Hello");
}
public static void main(String args[])
{ MyClass.sample(); } }
Output:
Hello
Static Fields − You can create a static field by using the keyword static. The static fields have the
same value in all the instances of the class. These are created and initialized when the class is loaded
for the first time. Just like static methods you can access static fields using the class name (without
instantiation).
• The java command-line argument is an argument i.e. passed at the time of running the
java program.
• The arguments passed from the console can be received in the java program and it can
be used as an input.
• So, it provides a convenient way to check the behavior of the program for the different
values.
• You can pass N (1,2,3 and so on) numbers of arguments from the command prompt
Simple example of command-line argument in java
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
• compile by > javac CommandLineExample.java
• run by > java CommandLineExample sonoo
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
} }
• compile by > javac A.java
• run by > java A sonoo jaiswal 1 3 abc
Syntax of varargs:
• Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can
directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the ways by
which Java achieves Run Time Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide all details is achieved through
inheritance. Abstraction only shows the functionality to the user.
}
INHERITANCE
• Syntax:
class Parent
{
//Data Members
//Methods
}
class Child extends Parent
{
//Data Members
//Methods
}
TYPES OF INHERITANCE
Single Inheritance
• When two or more than two classes inherits a single class, we call it hierarchical inheritance. In java a class can
be inherited by any number of classes, so in hierarchical inheritance, there can be any number of child classes, it's
not limited to two classes only. The program below shows an example of hierarchical inheritance.
• Syntax:
class A
{
}
class B extends A
{
}
class C extends A
{
}
Hierarchical Inheritance
Multiple Inheritance
• When a class inherits the features from more than one parent, we call it multiple inheritance.
• Multiple inheritance in java is not supported using classes, which means a class can not extend more than one
class.
• Multiple inheritance in java is supported through interfaces only, which means a class can inherit the features
from more than one interfaces. Java allows a class to implement any number of interfaces. The program below
shows an example of multiple inheritance.
• Syntax:
interface A
{
}
interface B
{
}
class C implements A,B
{
}
Multiple Inheritance
Hybrid Inheritance
• We can use super keyword to access the data member or field of parent class. This scenario occurs when a
derived class and base class has same data members.
Output:
Output
This is student class
This is person class
super() can be used to invoke immediate parent class constructor
Output
Person class Constructor
Student class Constructor
Protected Members
• A Java protected keyword is an access modifier. It can be assigned to variables, methods, constructors and
inner classes.
Key Points:
1. Accessing in the same class
2. Accessing in other classes of the same package
3. Accessing protected members of a class in its subclass in the same package
4. Accessing another class in a different package
5. Accessing in sub-class in a different package
Case 1: Accessing protected members in the same class
Case 2: Accessing protected members in other classes of the same package
We can access protected members of a class in another class that is present in the same package.
Case 3: Accessing protected members of a class in its subclass in the same package
We can access protected members of a class in its subclass if both are present in the same package.
class Sample
{
static protected String title = “JAVA";
protected int year = 2021;
protected void printYear()
{ Output
System.out.println("Its "+year+" !!");
} 2021
} Its 2021 !!
// Class 2 JAVA
public class Test extends Sample
{
public static void main(String[] args)
{
Sample sample = new Sample();
System.out.println(sample.year);
sample.printYear();
System.out.println(Sample.title);
}
}
Case 4: Accessing protected members in another class in a different package
We cannot access the protected members of a class in a class (non-subclass) that is present in a
different package.
package package2;
// Importing above package
// Package 1 import package1.Sample; Output:
package package1;
// Main class error: year has protected access in Sample
// Main class public class Test { System.out.println(sample.year);
public class Sample {
^
// Main driver method error: printYear() has protected access in Sample
static protected String title = “JAVA"; public static void main(String[] args) { sample.printYear();
protected int year = 2021;
^
Sample sample = new Sample(); error: title has protected access in Sample
// Protected method System.out.println(sample.year); System.out.println(Sample.title);
protected void printYear() { sample.printYear(); ^
System.out.println("Its "+year+" !!"); System.out.println(Sample.title);
} }
} }
Case 5: Accessing protected members in sub-class in a
different package
We can access protected members of a class in its subclass present in a different package. We will create
two classes. Sample class in package1 and Child class in package2. Child class extends Sample class.
package package2;
import package1.Sample;
package package1;
public class Child extends Sample
// Class {
public class Sample { void helper() Output
{
// Protected attributes System.out.println(year); 2021
static protected String title = “JAVA"; printYear(); Its 2021 !!
protected int year = 2021; System.out.println(Sample.title); JAVA
protected void printYear() }
{ public static void main(String[] args)
System.out.println("Its " + year + " !!"); {
} Child child = new Child();
} child.helper();
}
}
Calling Order of Constructors
When an object of a class is instantiated, the constructors of its superclass and then its own
constructors are executed. This is because constructors of the superclass are responsible for
initializing the state of the superclass. The state of the superclass can be used by the subclass to
initialize its own state.
Order of Execution in Single Level Inheritance
Order of Execution in Multi Level Inheritance
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 Java Method Overriding
Consider a scenario where Bank is a class that provides functionality to get the rate of interest.
However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks
could provide 8%, 7%, and 9% rate of interest.
Java Program to demonstrate the real scenario of Java
Method Overriding
//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
Java Program to demonstrate the real scenario of Java
Method Overriding(Contd.,)
2) Method overloading is performed within Method overriding occurs in two classes that
class. have IS-A (inheritance) relationship.
The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class
of java.
The Object class is beneficial if you want to refer any object whose type you don't know.
Notice that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type like
Employee, Student etc., we can use Object class reference to refer that object.
Example:
Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be compared, object can be cloned,
object can be notified etc.
Object class in Java(Contd.,)
Methods of Object class
Method Description
public final Class getClass() returns the Class class object of this object. The Class class can
further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws causes the current thread to wait for the specified milliseconds,
InterruptedException until another thread notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int nanos)throws causes the current thread to wait for the specified milliseconds and
InterruptedException nanoseconds, until another thread notifies (invokes notify() or
notifyAll() method).
public final void wait()throws InterruptedException causes the current thread to wait, until another thread notifies
(invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage
collected.
Abstract class in Java
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
Points to Remember
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the body of the method.
In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle and Circle classes.
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.
A factory method is a method that returns the instance of the class. We will learn about the
factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle
class will be invoked.
Example of Abstract Class(Contd.,)
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.
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface, but a class implements an
interface.
Example of Interface
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());
}} Output: ROI:9.15
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.
Example of 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");}