UNIT II
METHOD OVERLOADING AND
INHERITANCE
Method Overloading – Constructor Overloading – Objects as
Parameters – Returning Objects – Recursion – Access Control – static –
final – Nested and Inner Class – Inheritance: Basics – super – Multilevel
– Hierarchical – Method Overriding – Abstract class – final with
Inheritance.
Method Overloading
• If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
• How to perform method overloading in Java?
1. Overloading by changing the number of parameters
2. Method Overloading by changing the data type of
parameters
1. Overloading by changing the number of parameters
class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}
private static void display(int a, int b){
System.out.println("Arguments: " + a + " and " + b);
}
public static void main(String[] args) {
display(1);
display(1, 4);
}
}
Output
Arguments: 1
Arguments: 1 and 4
2. Method Overloading by changing the data type of parameters
class MethodOverloading {
// this method accepts int
private static void display(int a){
System.out.println("Got Integer data.");
}
// this method accepts String object
private static void display(String a){
System.out.println("Got String object.");
}
public static void main(String[] args) {
display(1);
display("Hello");
}
}
Output:
Got Integer data.
Got String object.
Method Overloading: changing no. of
arguments
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));
}}
Method Overloading: changing data type of
arguments
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));
}}
UNIT II
METHOD OVERLOADING AND
INHERITANCE
Method Overloading – Constructor Overloading – Objects as
Parameters – Returning Objects – Recursion – Access Control – static –
final – Nested and Inner Class – Inheritance: Basics – super – Multilevel
– Hierarchical – Method Overriding – Abstract class – final with
Inheritance.
• The constructor overloading can be defined as the concept of having
more than one constructor with different parameters so that every
constructor can perform a different task.
Default constructor (no-arg constructor)
• A constructor having no parameter is known as default constructor
and no-arg constructor.
class Main {
int i;
private Mainq() // constructor with no parameter
{
i = 5;
System.out.println("Constructor is called");
}
public static void main(String[] args)
{
// calling the constructor without any parameter
Main obj = new Main();
System.out.println("Value of i: " + obj.i);
}
}
Parameterized Constructors
• A constructor which has a specific number of parameters is called
parameterized constructor. Parameterized constructor is used to
provide different values to the distinct objects.
class Main {
String languages;
Main(String lang) // constructor accepting single value
{
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args)
{
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the
values of object
s1.display();
s2.display();
}
}
public class Student {
//instance variables of the class
int id;
String name;
Student(){
System.out.println("default constructor");
}
Student(int i, String n){
id = i;
name = n;
}
public static void main(String[] args)
{
//object creation
Student s = new Student();
System.out.println("nDefault Constructor values: n"
);
System.out.println("Student Id : "+s.id + "nStudent N
ame : "+s.name);
System.out.println("nParameterized Constructor val
ues: n");
Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "nStu
dent Name : "+student.name);
}
}
PROGRAM link
Output
this a default constructor
Default Constructor values:
Student Id : 0
Student Name : null
Parameterized Constructor values:
Student Id : 10
Student Name : David
Difference Between Constructor Overloading
and Method Overloading in Java
Constructor Overloading Method Overloading
Writing more than 1 constructor in a class with a
unique set of arguments is called as Constructor
Overloading
Writing more than one method within a class with a
unique set of arguments is called as method
overloading
All constructors will have the name of the class All methods must share the same name
Overloaded constructor will be executed at the time
of instantiating an object
An overloaded method if not static can only be called
after instantiating the object as per the requirement
An overloaded constructor cannot be static as a
constructor relates to the creation of an object
Overloaded method can be static, and it can be
accessed without creating an object
An overloaded constructor cannot be final as
constructor is not derived by subclasses it won’t make
sense
An overloaded method can be final to prevent
subclasses to override the method
An overloaded constructor can be private to prevent
using it for instantiating from outside of the class
An overloaded method can be private to prevent
access to call that method outside of the class
UNIT II
METHOD OVERLOADING AND
INHERITANCE
Method Overloading – Constructor Overloading – Objects as
Parameters – Returning Objects – Recursion – Access Control – static –
final – Nested and Inner Class – Inheritance: Basics – super – Multilevel
– Hierarchical – Method Overriding – Abstract class – final with
Inheritance.
Passing Object as Parameter in Function
• Object as an argument is use to establish communication between
two or more objects of same class as well as different class, i.e, user
can easily process data of two same or different objects within
function.
Passing Object as Parameter in Function
Passing Object as Parameter in Constructor
UNIT II
METHOD OVERLOADING AND
INHERITANCE
Method Overloading – Constructor Overloading – Objects as
Parameters – Returning Objects – Recursion – Access Control – static –
final – Nested and Inner Class – Inheritance: Basics – super – Multilevel
– Hierarchical – Method Overriding – Abstract class – final with
Inheritance.
Returning Objects
• In Java, a method can return any type of data, including class types
that you can create.
• For example, in the following Java program, the
method incrByTen() returns an object in which the value of a is ten
greater than it is in the invoking object.
Following are the important points must
remember while returning a value:
• The return type of the method and type of data returned at the end of the
method should be of the same type. For example, if a method is declared
with the float return type, the value returned should be of float type only.
• The variable that stores the returned value after the method is called
should be a similar data type otherwise, the data might get lost.
• If a method is declared with parameters, the sequence of the parameter
must be the same while declaration and method call.
Syntax:
return returnvalue;
class Test
{
int a;
Test(int i)
{
a = i;
}
Test incrByTen()
{
Test temp = new Test(a+10);
return temp;
}
}
public class JavaProgram
{
public static void main(String args[])
{
Test obj1 = new Test(2);
Test obj2;
obj2 = obj1.incrByTen();
System.out.println("obj1.a : " + obj1.a);
System.out.println("obj2.a : " + obj2.a);
obj2 = obj2.incrByTen();
System.out.println("obj2.a after second increase : " +
obj2.a);
}
}
UNIT II
METHOD OVERLOADING AND
INHERITANCE
Method Overloading – Constructor Overloading – Objects as Parameters
– Returning Objects – Recursion – Access Control – static – final –
Nested and Inner Class – Inheritance: Basics – super – Multilevel –
Hierarchical – Method Overriding – Abstract class – final with
Inheritance.
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.
Factorial program
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));
}
}
public class RecursionExample2 {
static int count=0;
static void p(){
count++;
if(count<=5){
System.out.println("hello "+count);
p();
}
}
public static void main(String[] args) {
p();
}
}
hello 1 hello 2 hello 3 hello 4 hello 5
hello 1
hello 2
hello 3
hello 4
hello 5
UNIT II
METHOD OVERLOADING AND
INHERITANCE
Method Overloading – Constructor Overloading – Objects as Parameters
– Returning Objects – Recursion – Access Control – static – final –
Nested and Inner Class – Inheritance: Basics – super – Multilevel –
Hierarchical – Method Overriding – Abstract class – final with
Inheritance.
• The access modifiers in Java specifies the accessibility or scope of a
field, method, constructor, or class. We can change the access level of
fields, constructors, methods, and class by applying the access
modifier on it.
• There are four types of Java access modifiers:
Types
• 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.
Types
• 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.
1) Private
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
• 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.
2) Default
package pack;
class A{
void msg()
{
System.out.println("Hello");
}
}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package.
3) Protected
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
• 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.
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.
4) Public
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
package mypack;
import pack.*;
class B{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
The public access modifier is accessible everywhere. It has the
widest scope among all other modifiers.
UNIT II
METHOD OVERLOADING AND
INHERITANCE
Method Overloading – Constructor Overloading – Objects as Parameters
– Returning Objects – Recursion – Access Control – static – final –
Nested and Inner Class – Inheritance: Basics – super – Multilevel –
Hierarchical – Method Overriding – Abstract class – final with
Inheritance.
Static keyword
• The static keyword in Java is used for memory management mainly.
We can apply static keyword with variables, methods, blocks
and nested classes
• The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested clas
1) Java static variable
• If you declare any variable as static, it is known as a static variable.
class Student{
int rollno;
String name;
String college="ITS";
}
Example of static variable
class Student
{
int rollno;//instance variable
String name;
static String college ="ITS";//static vari
able
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
void display (){
System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
• 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.
2) Java static method
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
void display(){System.out.println(rollno+" "+name+" "+college);}
}
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
UNIT II
METHOD OVERLOADING AND
INHERITANCE
Method Overloading – Constructor Overloading – Objects as Parameters
– Returning Objects – Recursion – Access Control – static – final –
Nested and Inner Class – Inheritance: Basics – super – Multilevel –
Hierarchical – Method Overriding – Abstract class – final with
Inheritance.
final
• The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
• variable
• method
• class
1) Java final variable
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
If you make any variable as final, you cannot
change the value of final variable(It will be
constant).
2) Java final method
class Bike{
final void run(){
System.out.println("running");}
}
class Honda extends Bike{
void run()
{
System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
If you make any method as final, you cannot override it.
3) Java final class
final class Bike
{
}
class Honda1 extends Bike{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
If you make any class as final, you cannot extend it.
UNIT II
METHOD OVERLOADING AND
INHERITANCE
Method Overloading – Constructor Overloading – Objects as Parameters
– Returning Objects – Recursion – Access Control – static – final –
Nested and Inner Class – Inheritance: Basics – super – Multilevel –
Hierarchical – Method Overriding – Abstract class – final with
Inheritance.
Nested and Inner Class
Inner Class
Java inner class is a class that is
declared inside the class or
interface.
Non-static nested classes are
known as inner classes.
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Nested and Inner Class
Nested Class (static)
public class Enclosing {
private static int x = 1;
public static class StaticNested {
private void run() {
// method implementation
}
}
@Test
public void test() {
Enclosing.StaticNested nested = new Enclosing.StaticNested();
nested.run();
}
}
UNIT II
METHOD OVERLOADING AND
INHERITANCE
Method Overloading – Constructor Overloading – Objects as Parameters
– Returning Objects – Recursion – Access Control – static – final –
Nested and Inner Class – Inheritance: Basics – super – Multilevel –
Hierarchical – Method Overriding – Abstract class – final with
Inheritance.
Inheritance:
Basics
• Inheritance in Java is a mechanism in which one object acquires all
the properties and behaviors of a parent object
Why use inheritance in java
• For Method Overriding
• For Code Reusability.
Terms used in Inheritance
1. Class:
2. Sub Class/Child Class:
3. Super Class/Parent Class:
4. Reusability
Syntax
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing
class.
Types of inheritance in java
• single,
• multilevel and
• hierarchical.
Types of inheritance in java
Multiple inheritance is not supported in Java through class.
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();
}}
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();
}}
Hierarchical Inheritance
class Animal{
void eat(){
System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){
System.out.println("meowing...");}
}
}}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
When two or more classes inherits a single class, it is
known as hierarchical inheritance
Why 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.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
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?
}
}
UNIT II
METHOD OVERLOADING AND
INHERITANCE
Method Overloading – Constructor Overloading – Objects as Parameters
– Returning Objects – Recursion – Access Control – static – final –
Nested and Inner Class – Inheritance: Basics – super – Multilevel –
Hierarchical – Method Overriding – Abstract class – final with
Inheritance.
Method Overriding
• 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
• 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).
Rules for Java Method Overriding
class Vehicle{
//defining a method
void run(){
System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){
System.out.println("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
UNIT II
METHOD OVERLOADING AND
INHERITANCE
Method Overloading – Constructor Overloading – Objects as Parameters
– Returning Objects – Recursion – Access Control – static – final –
Nested and Inner Class – Inheritance: Basics – super – Multilevel –
Hierarchical – Method Overriding – Abstract class – final with
Inheritance.
Abstract class
• 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.
• There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)
Abstract class
• A class which is declared as abstract is known as an abstract class.
• It can have abstract and non-abstract methods. It needs to be
extended and its method implemented. It cannot be instantiated.
abstract class A
{
}
Abstract Method in Java
• A method which is declared as abstract and does not have
implementation is known as an abstract method.
abstract void printStatus(); //no method body and abstract
Example
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike
{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
UNIT II
METHOD OVERLOADING AND
INHERITANCE
Method Overloading – Constructor Overloading – Objects as Parameters
– Returning Objects – Recursion – Access Control – static – final –
Nested and Inner Class – Inheritance: Basics – super – Multilevel –
Hierarchical – Method Overriding – Abstract class – final with
Inheritance.
final with Inheritance.
• The final keyword is final that is we cannot change.
• We can use final keywords for variables, methods, and class.
• If we use the final keyword for the inheritance that is if we declare
any method with the final keyword in the base class so the
implementation of the final method will be the same as in derived
class.
• We can declare the final method in any subclass for which we want
that if any other class extends this subclass.
// Declaring Parent class
class Parent {
final void parent() {
System.out.println("Hello , we are in parent method");
}
}
// Declaring Child class by extending Parent class
class Child extends Parent {
void child() {
System.out.println("Hello , we are in child method");
}
}
class Test {
public static void main(String[] args)
{
Parent p = new Parent();
p.parent();
Child c = new Child();
c.child();
c.parent();
}
}
• Create a class Account with two overloaded constructors. First
constructor is used for initializing, name of account holder, account
number and initial amount in account. Second constructor is used
for initializing name of account holder, account number, addresses,
type of account and current balance. Account class is having methods
Deposit (), Withdraw (), and Get_Balance().Make necessary
assumption for data members and return types of the methods.
Create objects of Account class and use them.
First constructor is used for initializing, name of account holder, account number and
initial amount in account. Second constructor is used for initializing name of account
holder, account number, addresses, type of account and current balance.
class account
{
String name,address,type;
int accno,bal;
account(String n,int no,int b)
{
name=n;
accno=no;
bal=b; }
account(String n,int no,String addr,String t,int b)
{
name=n; accno=no;
address=addr;
type=t; bal=b;
}
Account class is having methods Deposit (), Withdraw (), and Get_Balance().Make
necessary assumption for data members and return types of the methods. Create
objects of Account class and use them.
void deposite(int a) {
bal+=a;
}
void withdraw(int a) {
bal-=a;
}
int getbalance()
{
return(bal);
}
void show()
{
System.out.println(" ACCOUNT DETAILS");
System.out.println("Name : "+name);
System.out.println("Account No : "+accno);
System.out.println("Address : "+address);
System.out.println("Type : "+type);
System.out.println("Balance : "+bal);
}
}
Make necessary assumption for data members and return types of the
methods. Create objects of Account class and use them.
class Mainclass
{
public static void main(String arg[])throws Exception
{
account a1=new account("Anil",555,5000);
account a2=new account("Anil",666,"Tirur","Current account",1000);
a1.address="Calicut";
a1.type="fixed deposite";
a1.deposite(5000);
a2.withdraw(350);
a2.deposite(a2.getbalance());
a1.show();
a2.show();
}
}
Additional Programs
• a) Write a program in Java with class Rectangle with the data fields
width, length, area and color .The length, width and area are of
double type and color is of string type. The methods are set_ length
(), set_width (), set_ color(), and find_ area (). Create two object of
Rectangle and use them
• Write a Java program to compute the specified expressions and print
the output.
• Specified Expression :
(25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5)
public class Exercise9 {
public static void main(String[] arg) {
System.out.println((25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5));
}
}
Write a Java program that takes five numbers as input to calculate and
print the average of the numbers.
Test Data:
Input first number: 10
Input second number: 20
Input third number: 30
Input fourth number: 40
Enter fifth number: 50
import java.util.Scanner;
public class Exercise12 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
int num1 = in.nextInt();
System.out.print("Input second number: ");
int num2 = in.nextInt();
System.out.print("Input third number: ");
int num3 = in.nextInt();
System.out.print("Input fourth number: ");
int num4 = in.nextInt();
System.out.print("Enter fifth number: ");
int num5 = in.nextInt();
System.out.println("Average of five numbers is: " +
(num1 + num2 + num3 + num4 + num5) / 5);
}
}
Write a Java program to swap two variables.
public class Exercise15 {
public static void main(String[] args) {
int a, b, temp;
a = 15;
b = 27;
System.out.println("Before swapping : a, b = "+a+", "+ + b);
temp = a;
a = b;
b = temp;
System.out.println("After swapping : a, b = "+a+", "+ + b);
}
}
Write a Java program to print the ascii value
of a given character.
public class Exercise41 {
public static void main(String[] String) {
int chr = 'Z';
System.out.println("The ASCII value of Z is :"+chr);
}
}
What is the output of this program?
class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
System.out.println(i);
}
}
}

U2 JAVA.pptx

  • 1.
    UNIT II METHOD OVERLOADINGAND INHERITANCE Method Overloading – Constructor Overloading – Objects as Parameters – Returning Objects – Recursion – Access Control – static – final – Nested and Inner Class – Inheritance: Basics – super – Multilevel – Hierarchical – Method Overriding – Abstract class – final with Inheritance.
  • 2.
    Method Overloading • Ifa class has multiple methods having same name but different in parameters, it is known as Method Overloading. • How to perform method overloading in Java? 1. Overloading by changing the number of parameters 2. Method Overloading by changing the data type of parameters
  • 4.
    1. Overloading bychanging the number of parameters class MethodOverloading { private static void display(int a){ System.out.println("Arguments: " + a); } private static void display(int a, int b){ System.out.println("Arguments: " + a + " and " + b); } public static void main(String[] args) { display(1); display(1, 4); } } Output Arguments: 1 Arguments: 1 and 4
  • 5.
    2. Method Overloadingby changing the data type of parameters class MethodOverloading { // this method accepts int private static void display(int a){ System.out.println("Got Integer data."); } // this method accepts String object private static void display(String a){ System.out.println("Got String object."); } public static void main(String[] args) { display(1); display("Hello"); } } Output: Got Integer data. Got String object.
  • 6.
    Method Overloading: changingno. of arguments 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)); }} Method Overloading: changing data type of arguments 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)); }}
  • 7.
    UNIT II METHOD OVERLOADINGAND INHERITANCE Method Overloading – Constructor Overloading – Objects as Parameters – Returning Objects – Recursion – Access Control – static – final – Nested and Inner Class – Inheritance: Basics – super – Multilevel – Hierarchical – Method Overriding – Abstract class – final with Inheritance.
  • 8.
    • The constructoroverloading can be defined as the concept of having more than one constructor with different parameters so that every constructor can perform a different task.
  • 10.
    Default constructor (no-argconstructor) • A constructor having no parameter is known as default constructor and no-arg constructor.
  • 11.
    class Main { inti; private Mainq() // constructor with no parameter { i = 5; System.out.println("Constructor is called"); } public static void main(String[] args) { // calling the constructor without any parameter Main obj = new Main(); System.out.println("Value of i: " + obj.i); } }
  • 12.
    Parameterized Constructors • Aconstructor which has a specific number of parameters is called parameterized constructor. Parameterized constructor is used to provide different values to the distinct objects.
  • 13.
    class Main { Stringlanguages; Main(String lang) // constructor accepting single value { languages = lang; System.out.println(languages + " Programming Language"); } public static void main(String[] args) { // call constructor by passing a single value Main obj1 = new Main("Java"); Main obj2 = new Main("Python"); Main obj3 = new Main("C"); } }
  • 14.
    class Student4{ int id; Stringname; //creating a parameterized constructor Student4(int i,String n){ id = i; name = n; } //method to display the values void display(){ System.out.println(id+" "+name); } public static void main(String args[]){ //creating objects and passing values Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); //calling method to display the values of object s1.display(); s2.display(); } }
  • 15.
    public class Student{ //instance variables of the class int id; String name; Student(){ System.out.println("default constructor"); } Student(int i, String n){ id = i; name = n; } public static void main(String[] args) { //object creation Student s = new Student(); System.out.println("nDefault Constructor values: n" ); System.out.println("Student Id : "+s.id + "nStudent N ame : "+s.name); System.out.println("nParameterized Constructor val ues: n"); Student student = new Student(10, "David"); System.out.println("Student Id : "+student.id + "nStu dent Name : "+student.name); } } PROGRAM link
  • 16.
    Output this a defaultconstructor Default Constructor values: Student Id : 0 Student Name : null Parameterized Constructor values: Student Id : 10 Student Name : David
  • 17.
    Difference Between ConstructorOverloading and Method Overloading in Java
  • 18.
    Constructor Overloading MethodOverloading Writing more than 1 constructor in a class with a unique set of arguments is called as Constructor Overloading Writing more than one method within a class with a unique set of arguments is called as method overloading All constructors will have the name of the class All methods must share the same name Overloaded constructor will be executed at the time of instantiating an object An overloaded method if not static can only be called after instantiating the object as per the requirement An overloaded constructor cannot be static as a constructor relates to the creation of an object Overloaded method can be static, and it can be accessed without creating an object An overloaded constructor cannot be final as constructor is not derived by subclasses it won’t make sense An overloaded method can be final to prevent subclasses to override the method An overloaded constructor can be private to prevent using it for instantiating from outside of the class An overloaded method can be private to prevent access to call that method outside of the class
  • 19.
    UNIT II METHOD OVERLOADINGAND INHERITANCE Method Overloading – Constructor Overloading – Objects as Parameters – Returning Objects – Recursion – Access Control – static – final – Nested and Inner Class – Inheritance: Basics – super – Multilevel – Hierarchical – Method Overriding – Abstract class – final with Inheritance.
  • 20.
    Passing Object asParameter in Function • Object as an argument is use to establish communication between two or more objects of same class as well as different class, i.e, user can easily process data of two same or different objects within function.
  • 21.
    Passing Object asParameter in Function
  • 22.
    Passing Object asParameter in Constructor
  • 23.
    UNIT II METHOD OVERLOADINGAND INHERITANCE Method Overloading – Constructor Overloading – Objects as Parameters – Returning Objects – Recursion – Access Control – static – final – Nested and Inner Class – Inheritance: Basics – super – Multilevel – Hierarchical – Method Overriding – Abstract class – final with Inheritance.
  • 24.
    Returning Objects • InJava, a method can return any type of data, including class types that you can create. • For example, in the following Java program, the method incrByTen() returns an object in which the value of a is ten greater than it is in the invoking object.
  • 25.
    Following are theimportant points must remember while returning a value: • The return type of the method and type of data returned at the end of the method should be of the same type. For example, if a method is declared with the float return type, the value returned should be of float type only. • The variable that stores the returned value after the method is called should be a similar data type otherwise, the data might get lost. • If a method is declared with parameters, the sequence of the parameter must be the same while declaration and method call. Syntax: return returnvalue;
  • 26.
    class Test { int a; Test(inti) { a = i; } Test incrByTen() { Test temp = new Test(a+10); return temp; } } public class JavaProgram { public static void main(String args[]) { Test obj1 = new Test(2); Test obj2; obj2 = obj1.incrByTen(); System.out.println("obj1.a : " + obj1.a); System.out.println("obj2.a : " + obj2.a); obj2 = obj2.incrByTen(); System.out.println("obj2.a after second increase : " + obj2.a); } }
  • 27.
    UNIT II METHOD OVERLOADINGAND INHERITANCE Method Overloading – Constructor Overloading – Objects as Parameters – Returning Objects – Recursion – Access Control – static – final – Nested and Inner Class – Inheritance: Basics – super – Multilevel – Hierarchical – Method Overriding – Abstract class – final with Inheritance.
  • 28.
    Recursion • Recursion injava 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.
  • 29.
    Factorial program public classRecursionExample3 { 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)); } }
  • 31.
    public class RecursionExample2{ static int count=0; static void p(){ count++; if(count<=5){ System.out.println("hello "+count); p(); } } public static void main(String[] args) { p(); } }
  • 32.
    hello 1 hello2 hello 3 hello 4 hello 5 hello 1 hello 2 hello 3 hello 4 hello 5
  • 33.
    UNIT II METHOD OVERLOADINGAND INHERITANCE Method Overloading – Constructor Overloading – Objects as Parameters – Returning Objects – Recursion – Access Control – static – final – Nested and Inner Class – Inheritance: Basics – super – Multilevel – Hierarchical – Method Overriding – Abstract class – final with Inheritance.
  • 34.
    • The accessmodifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it. • There are four types of Java access modifiers:
  • 35.
    Types • Private: Theaccess 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.
  • 36.
    Types • Protected: Theaccess 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.
  • 38.
    1) Private class A { privateint data=40; private void msg() { System.out.println("Hello java"); } } public class Simple { public static void main(String args[]){ A obj=new A(); System.out.println(obj.data);//Compile Time Error obj.msg();//Compile Time Error } • 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.
  • 39.
    2) Default package pack; classA{ void msg() { System.out.println("Hello"); } } package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A();//Compile Time Error obj.msg();//Compile Time Error } } If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package.
  • 40.
    3) Protected package pack; publicclass A { protected void msg() { System.out.println("Hello"); } } package mypack; import pack.*; class B extends A { public static void main(String args[]) { B obj = new B(); obj.msg(); } } • 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. 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.
  • 41.
    4) Public package pack; publicclass A { public void msg() { System.out.println("Hello"); } } package mypack; import pack.*; class B{ public static void main(String args[]) { A obj = new A(); obj.msg(); } } The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
  • 42.
    UNIT II METHOD OVERLOADINGAND INHERITANCE Method Overloading – Constructor Overloading – Objects as Parameters – Returning Objects – Recursion – Access Control – static – final – Nested and Inner Class – Inheritance: Basics – super – Multilevel – Hierarchical – Method Overriding – Abstract class – final with Inheritance.
  • 43.
    Static keyword • Thestatic keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes • The static can be: 1. Variable (also known as a class variable) 2. Method (also known as a class method) 3. Block 4. Nested clas
  • 44.
    1) Java staticvariable • If you declare any variable as static, it is known as a static variable. class Student{ int rollno; String name; String college="ITS"; }
  • 45.
    Example of staticvariable class Student { int rollno;//instance variable String name; static String college ="ITS";//static vari able //constructor Student(int r, String n){ rollno = r; name = n; } void display (){ System.out.println(rollno+" "+name+" "+college);} } //Test class to show the values of objects public class TestStaticVariable1{ public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); s1.display(); s2.display(); } }
  • 46.
    • If youapply 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.
  • 47.
    2) Java staticmethod class Student{ int rollno; String name; static String college = "ITS"; //static method to change the value of static variable static void change(){ college = "BBDIT"; } //constructor to initialize the variable Student(int r, String n){ rollno = r; name = n; } void display(){System.out.println(rollno+" "+name+" "+college);} } public class TestStaticMethod{ public static void main(String args[]){ Student.change();//calling change method //creating objects Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); Student s3 = new Student(333,"Sonoo"); //calling display method s1.display(); s2.display(); s3.display(); } }
  • 48.
    UNIT II METHOD OVERLOADINGAND INHERITANCE Method Overloading – Constructor Overloading – Objects as Parameters – Returning Objects – Recursion – Access Control – static – final – Nested and Inner Class – Inheritance: Basics – super – Multilevel – Hierarchical – Method Overriding – Abstract class – final with Inheritance.
  • 49.
    final • The finalkeyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: • variable • method • class
  • 50.
    1) Java finalvariable class Bike9{ final int speedlimit=90;//final variable void run(){ speedlimit=400; } public static void main(String args[]){ Bike9 obj=new Bike9(); obj.run(); } }//end of class If you make any variable as final, you cannot change the value of final variable(It will be constant).
  • 51.
    2) Java finalmethod class Bike{ final void run(){ System.out.println("running");} } class Honda extends Bike{ void run() { System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } If you make any method as final, you cannot override it.
  • 52.
    3) Java finalclass final class Bike { } class Honda1 extends Bike{ void run() { System.out.println("running safely with 100kmph"); } public static void main(String args[]){ Honda1 honda= new Honda1(); honda.run(); } } If you make any class as final, you cannot extend it.
  • 53.
    UNIT II METHOD OVERLOADINGAND INHERITANCE Method Overloading – Constructor Overloading – Objects as Parameters – Returning Objects – Recursion – Access Control – static – final – Nested and Inner Class – Inheritance: Basics – super – Multilevel – Hierarchical – Method Overriding – Abstract class – final with Inheritance.
  • 54.
    Nested and InnerClass Inner Class Java inner class is a class that is declared inside the class or interface. Non-static nested classes are known as inner classes. class Java_Outer_class { //code class Java_Inner_class { //code } }
  • 55.
    Nested and InnerClass Nested Class (static) public class Enclosing { private static int x = 1; public static class StaticNested { private void run() { // method implementation } } @Test public void test() { Enclosing.StaticNested nested = new Enclosing.StaticNested(); nested.run(); } }
  • 56.
    UNIT II METHOD OVERLOADINGAND INHERITANCE Method Overloading – Constructor Overloading – Objects as Parameters – Returning Objects – Recursion – Access Control – static – final – Nested and Inner Class – Inheritance: Basics – super – Multilevel – Hierarchical – Method Overriding – Abstract class – final with Inheritance.
  • 57.
    Inheritance: Basics • Inheritance inJava is a mechanism in which one object acquires all the properties and behaviors of a parent object
  • 58.
    Why use inheritancein java • For Method Overriding • For Code Reusability. Terms used in Inheritance 1. Class: 2. Sub Class/Child Class: 3. Super Class/Parent Class: 4. Reusability
  • 59.
    Syntax class Subclass-name extendsSuperclass-name { //methods and fields } The extends keyword indicates that you are making a new class that derives from an existing class.
  • 60.
    Types of inheritancein java • single, • multilevel and • hierarchical.
  • 61.
    Types of inheritancein java Multiple inheritance is not supported in Java through class.
  • 62.
    Single Inheritance class Animal { voideat(){ 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(); }}
  • 63.
    Multilevel Inheritance class Animal{ voideat(){ 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(); }}
  • 64.
    Hierarchical Inheritance class Animal{ voideat(){ System.out.println("eating...");} } class Dog extends Animal{ void bark(){ System.out.println("barking...");} } class Cat extends Animal{ void meow(){ System.out.println("meowing...");} } }} class TestInheritance3{ public static void main(String args[]){ Cat c=new Cat(); c.meow(); c.eat(); //c.bark();//C.T.Error When two or more classes inherits a single class, it is known as hierarchical inheritance
  • 65.
    Why multiple inheritanceis 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.
  • 66.
    class A{ void msg(){System.out.println("Hello");} } classB{ void msg(){System.out.println("Welcome");} } 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? } }
  • 67.
    UNIT II METHOD OVERLOADINGAND INHERITANCE Method Overloading – Constructor Overloading – Objects as Parameters – Returning Objects – Recursion – Access Control – static – final – Nested and Inner Class – Inheritance: Basics – super – Multilevel – Hierarchical – Method Overriding – Abstract class – final with Inheritance.
  • 68.
    Method Overriding • Ifsubclass (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.
  • 69.
    Usage of JavaMethod 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). Rules for Java Method Overriding
  • 70.
    class Vehicle{ //defining amethod void run(){ System.out.println("Vehicle is running");} } //Creating a child class class Bike2 extends Vehicle{ //defining the same method as in the parent class void run(){ System.out.println("Bike is running safely"); } public static void main(String args[]){ Bike2 obj = new Bike2();//creating object obj.run();//calling method } }
  • 71.
    UNIT II METHOD OVERLOADINGAND INHERITANCE Method Overloading – Constructor Overloading – Objects as Parameters – Returning Objects – Recursion – Access Control – static – final – Nested and Inner Class – Inheritance: Basics – super – Multilevel – Hierarchical – Method Overriding – Abstract class – final with Inheritance.
  • 72.
    Abstract class • Abstractionis 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. • There are two ways to achieve abstraction in java Abstract class (0 to 100%) Interface (100%)
  • 73.
    Abstract class • Aclass which is declared as abstract is known as an abstract class. • It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated. abstract class A { }
  • 74.
    Abstract Method inJava • A method which is declared as abstract and does not have implementation is known as an abstract method. abstract void printStatus(); //no method body and abstract
  • 75.
    Example abstract class Bike{ abstractvoid run(); } class Honda4 extends Bike { void run(){System.out.println("running safely");} public static void main(String args[]){ Bike obj = new Honda4(); obj.run(); } }
  • 76.
    UNIT II METHOD OVERLOADINGAND INHERITANCE Method Overloading – Constructor Overloading – Objects as Parameters – Returning Objects – Recursion – Access Control – static – final – Nested and Inner Class – Inheritance: Basics – super – Multilevel – Hierarchical – Method Overriding – Abstract class – final with Inheritance.
  • 77.
    final with Inheritance. •The final keyword is final that is we cannot change. • We can use final keywords for variables, methods, and class. • If we use the final keyword for the inheritance that is if we declare any method with the final keyword in the base class so the implementation of the final method will be the same as in derived class. • We can declare the final method in any subclass for which we want that if any other class extends this subclass.
  • 78.
    // Declaring Parentclass class Parent { final void parent() { System.out.println("Hello , we are in parent method"); } } // Declaring Child class by extending Parent class class Child extends Parent { void child() { System.out.println("Hello , we are in child method"); } } class Test { public static void main(String[] args) { Parent p = new Parent(); p.parent(); Child c = new Child(); c.child(); c.parent(); } }
  • 79.
    • Create aclass Account with two overloaded constructors. First constructor is used for initializing, name of account holder, account number and initial amount in account. Second constructor is used for initializing name of account holder, account number, addresses, type of account and current balance. Account class is having methods Deposit (), Withdraw (), and Get_Balance().Make necessary assumption for data members and return types of the methods. Create objects of Account class and use them.
  • 80.
    First constructor isused for initializing, name of account holder, account number and initial amount in account. Second constructor is used for initializing name of account holder, account number, addresses, type of account and current balance. class account { String name,address,type; int accno,bal; account(String n,int no,int b) { name=n; accno=no; bal=b; } account(String n,int no,String addr,String t,int b) { name=n; accno=no; address=addr; type=t; bal=b; }
  • 81.
    Account class ishaving methods Deposit (), Withdraw (), and Get_Balance().Make necessary assumption for data members and return types of the methods. Create objects of Account class and use them. void deposite(int a) { bal+=a; } void withdraw(int a) { bal-=a; } int getbalance() { return(bal); } void show() { System.out.println(" ACCOUNT DETAILS"); System.out.println("Name : "+name); System.out.println("Account No : "+accno); System.out.println("Address : "+address); System.out.println("Type : "+type); System.out.println("Balance : "+bal); } }
  • 82.
    Make necessary assumptionfor data members and return types of the methods. Create objects of Account class and use them. class Mainclass { public static void main(String arg[])throws Exception { account a1=new account("Anil",555,5000); account a2=new account("Anil",666,"Tirur","Current account",1000); a1.address="Calicut"; a1.type="fixed deposite"; a1.deposite(5000); a2.withdraw(350); a2.deposite(a2.getbalance()); a1.show(); a2.show(); } }
  • 83.
    Additional Programs • a)Write a program in Java with class Rectangle with the data fields width, length, area and color .The length, width and area are of double type and color is of string type. The methods are set_ length (), set_width (), set_ color(), and find_ area (). Create two object of Rectangle and use them
  • 85.
    • Write aJava program to compute the specified expressions and print the output. • Specified Expression : (25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5)
  • 86.
    public class Exercise9{ public static void main(String[] arg) { System.out.println((25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5)); } }
  • 87.
    Write a Javaprogram that takes five numbers as input to calculate and print the average of the numbers. Test Data: Input first number: 10 Input second number: 20 Input third number: 30 Input fourth number: 40 Enter fifth number: 50
  • 88.
    import java.util.Scanner; public classExercise12 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input first number: "); int num1 = in.nextInt(); System.out.print("Input second number: "); int num2 = in.nextInt(); System.out.print("Input third number: "); int num3 = in.nextInt(); System.out.print("Input fourth number: "); int num4 = in.nextInt(); System.out.print("Enter fifth number: "); int num5 = in.nextInt(); System.out.println("Average of five numbers is: " + (num1 + num2 + num3 + num4 + num5) / 5); } }
  • 89.
    Write a Javaprogram to swap two variables. public class Exercise15 { public static void main(String[] args) { int a, b, temp; a = 15; b = 27; System.out.println("Before swapping : a, b = "+a+", "+ + b); temp = a; a = b; b = temp; System.out.println("After swapping : a, b = "+a+", "+ + b); } }
  • 90.
    Write a Javaprogram to print the ascii value of a given character. public class Exercise41 { public static void main(String[] String) { int chr = 'Z'; System.out.println("The ASCII value of Z is :"+chr); } }
  • 91.
    What is theoutput of this program? class Main { public static void main(String[] args) { int n = 5; // for loop for (int i = 1; i <= n; ++i) { System.out.println(i); } } }