Overloading Methods

In object-oriented terms overriding means to override the functionality of the existing method. The benefit of overriding is the ability to define a behavior that defines some class types, which means a sub class can be implement a parent class Method based on its requirement method is the derived class can Implement appearance class methods based on its requirement method in the derived class can have similar mean, have to be class. This is to ensure that the method, when called in the program, works the scene for both the base class and derived class. Overriding interest creation of methods in the sub class that has the same signature that is names number and type of arguments as the method in superclass, when a method is called an object, the Java compiler first searches for the method in the class of the object. If the method is not found, then, the compiler searches for the method in hierarchy until the method is found.

Example:

class Animal {

    public void printSound() {

        System.out.println(“Animal sound”);

    }}

class Dog extends Animal {

    public void printDogSound() {

        System.out.println(“Dogs bark”);

    }}

class Cat extends Animal {

    public void printCatSound() {

        System.out.println(“Cats meow”);

    }}

class Pig extends Animal {

    public void printPigSound() {

        System.out.println(“Pigs snort”);

    }}

Constructed overloading in Java:

Constructed overloading is a technique in which A class can have any number of constructors That are different in parameter lists. The compiler differentiates these constructors by taking in two account/parenthesis in constructor. The number of parameters lift and the type, overloading means adding the additional parameters to the constructor.

Constructor overloading allows to add more constructors inside a class. Constructed overloading is the way of having more than one constructor, which does different tasks.

Example:

class Student {

    private String stuname;

    private String stuid;

    private int stuage;

    Student() {

        System.out.println(“this a default constructor”);

    }

    Student(String stuname, String stuid, int stuage) {

        this.stuname = stuname;

        this.stuid = stuid;

        this.stuage = stuage;

    }

    public String getStudentName() {

        return stuname;

    }

    public String getStudentId() {

        return stuid;

    }

    public int getStudentAge() {

        return stuage;

    }

}

public class Constructor_OverloadingExample {

    public static void main(String[] args) {

        Student stu = new Student();// calling the default constructor

        Student student = new Student(“Khubaib”, “CSC-17F-129”, 22);

        System.out.println(“Student Name: ” + student.getStudentName());

        System.out.println(“Student ID: ” + student.getStudentId());

        System.out.println(“Student Age: ” + student.getStudentAge());

    }

}

Example 2:

class Box {

    double width, height, depth;

    Box(double w, double h, double d) {

        width = w;

        height = h;

        depth = d;

    }

    // constructor used when no dimensions

    // specified

    Box() {

        width = height = depth = 0;

    }

    // constructor used when cube is created

    Box(double len) {

        width = height = depth = len;

    }

    // compute and return volume

    double volume() {

        return width * height * depth;

    }

}

// Driver code

public class Test {

    public static void main(String args[]) {

        // create boxes using the various

        // constructors

        Box mybox1 = new Box(10, 20, 15);

        Box mybox2 = new Box();

        Box mycube = new Box(7);

        double vol;

        // get volume of first box

        vol = mybox1.volume();

        System.out.println(” Volume of mybox1 is ” + vol);

        // get volume of second box

        vol = mybox2.volume();

        System.out.println(” Volume of mybox2 is ” + vol);

        // get volume of cube

        vol = mycube.volume();

        System.out.println(” Volume of mycube is ” + vol);

    }

}

Important point related to constructor overloading:

Using Object as parameters:

In Java, When a primitive type is passed to a method, it is done by use of call-by-value. Objects are implicitly passed by use of call-by-reference.

This means when we pass primitive data types to method it will pass only values to function parameters so any change made in parameter will not affect the value of actual parameters.

Whereas Objects in java are reference variables, so for objects a value which is the reference to the object is passed. Hence the whole object is not passed but its referenced gets passed. All modification to the object in the method would modify the object in the Heap.

Passing Object as Parameter in Function

class Add

{

                int a;

                int b;

                Add(int x,int y)// parametrized constructor

                {

                                a=x;

                                b=y;

                }

                void sum(Add A1) // object  ‘A1’ passed as parameter in function ‘sum’

                {

                                int sum1=A1.a+A1.b;

                                System.out.println(“Sum of a and b :”+sum1);

                }

}

public class classExAdd

{

                public static void main(String arg[])

                {

                                Add A=new Add(5,8);

                                /* Calls  the parametrized constructor

                                with set of parameters*/

                                A.sum(A);

                }

}

Output

Sum of a and b :13

While creating a variable of class type, we only create a reference to an object.

When we pass this reference to a function, the parameters that receive it will refer to the same object as that referred to by the argument.

Passing Object as Parameter in Constructor

One of the most common uses of objects as parameters involves constructors. A constructor creates a new object initially the same as passed object. It is also used to initialize private members.

class Add

{

                private int a,b;

                Add(Add A)

                {

                                a=A.a;

                                b=A.b;

                }

                Add(int x,int y)

                {

                                a=x;

                                b=y;

                }

                void sum()

                {

                                int sum1=a+b;

                                System.out.println(“Sum of a and b :”+sum1);

                }

}

class ExAddcons

{

                public static void main(String arg[])

                {

                                Add A=new Add(15,8);

                                Add A1=new Add(A);

                                A1.sum();

                }

}

Output

Sum of a and b : 2

A CLOSER LOOK AT ARGUMENT PASSING

There are two ways that a computer language can pass an argument to a subroutine. The first way is call-by-value. This method copies the value of an argument into the formal parameter of the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the argument. The second way an argument can be passed is call-by-reference. In Java, when you pass a simple type to a method, it is passed by value. Thus, what occurs to the parameter that receives the argument has no effect outside the method.

Call-By-Value

Pass by value in java means passing a copy of the value to be passed.  In Java the arguments are always passed by value.In case of call by value original value is not changed.

Example of call by value in java

class Operation

 int data=50; 

 void change(int data)

 data=data+100;//changes will be in the local variable only 

 } 

 public static void main(String args[])

   Operation op=new Operation(); 

   System.out.println(“before change “+op.data); 

   op.change(500); 

   System.out.println(“after change “+op.data); 

 } 

Output:

before change 50

after change 50

Call-By-Reference

Pass by reference in java means the passing the address itself.In case of call by reference original value is changed if we made changes in the called method. If we pass object in place of any primitive value, original value will be changed.

Example of call-by-reference in java

class Operation2

 int data=50; 

 void change(Operation2 op)

 op.data=op.data+100;//changes will be in the instance variable 

 } 

 public static void main(String args[])

   Operation2 op=new Operation2(); 

   System.out.println(“before change “+op.data); 

   op.change(op);//passing object 

   System.out.println(“after change “+op.data); 

 } 

Output:

before change 50

after change 150 

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.

Example

// Class 1

class ObjectReturnDemo {

    int a;

    // Constructor

    ObjectReturnDemo(int i) { a = i; }

    // Method returns an object

    ObjectReturnDemo incrByTen()

    {

        ObjectReturnDemo temp

            = new ObjectReturnDemo(a + 10);

        return temp;

    }

}

// Class 2

// Main class

public class GFG {

    // Main driver method

    public static void main(String args[])

    {

        // Creating object of class1 inside main() method

        ObjectReturnDemo ob1 = new ObjectReturnDemo(2);

        ObjectReturnDemo ob2;

        ob2 = ob1.incrByTen();

        System.out.println(“ob1.a: ” + ob1.a);

        System.out.println(“ob2.a: ” + ob2.a);

    }

}

Output

ob1.a: 2

ob2.a: 12

Note: When an object reference is passed to a method, the reference itself is passed by use of call-by-value. However, since the value being passed refers to an object, the copy of that value will still refer to the same object that its corresponding argument does. That’s why we said that java is strictly pass-by-value.

Recursion in Java

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.

Syntax:

returntype methodname(){ 

//code to be executed 

methodname();//calling same method 

Example:

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();

    }

}

Output:

hello 1

hello 2

hello 3

hello 4

hello 5

Example 2: (Fibonacci Series)

public class RecursionExample4 { 

    static int n1=0,n2=1,n3=0;     

     static void printFibo(int count){     

        if(count>0){     

             n3 = n1 + n2;     

             n1 = n2;     

             n2 = n3;     

             System.out.print(” “+n3);    

             printFibo(count-1);     

         }     

     }       

public static void main(String[] args) { 

    int count=15;     

      System.out.print(n1+” “+n2);//printing 0 and 1     

      printFibo(count-2);//n-2 because 2 numbers are already printed    

Output:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Access Modifiers in Java:

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. 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:

Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.

Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.

Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.

Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we are going to learn the access modifiers only.

) Private

The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data member and private method. We are accessing these private members from outside the class, so there is a compile-time error.

class A{ 

private int data=40; 

private void msg(){System.out.println(“Hello java”);} 

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 

   } 

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:

class A{ 

private A(){}//private constructor 

void msg(){System.out.println(“Hello java”);} 

public class Simple{ 

 public static void main(String args[]){ 

   A obj=new A();//Compile Time Error 

 } 

Note: A class cannot be private or protected except nested class.

2) Default

If you don’t use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package.

//save by A.java 

package pack; 

class A{ 

  void msg(){System.out.println(“Hello”);} 

//save by B.java 

package mypack; 

import pack.*; 

class B{ 

  public static void main(String args[]){ 

   A obj = new A();//Compile Time Error 

   obj.msg();//Compile Time Error 

  } 

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.

3) Protected

The protected access modifier is accessible within package and outside the package but through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can’t be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.

//save by A.java 

package pack; 

public class A{ 

protected void msg(){System.out.println(“Hello”);} 

//save by B.java 

package mypack; 

import pack.*; 

class B extends A{ 

  public static void main(String args[]){ 

   B obj = new B(); 

   obj.msg(); 

  } 

Output:Hello

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Example of public access modifier

//save by A.java 

package pack; 

public class A{ 

public void msg(){System.out.println(“Hello”);} 

//save by B.java 

package mypack; 

import pack.*; 

class B{ 

  public static void main(String args[]){ 

   A obj = new A(); 

   obj.msg(); 

  } 

Output:Hello

The Static Modifier

Static Variables

The static keyword is used to create variables that will exist independently of any instances created for the class. Only one copy of the static variable exists regardless of the number of instances of the class.

Static variables are also known as class variables. Local variables cannot be declared static.

Static Methods

The static keyword is used to create methods that will exist independently of any instances created for the class.

Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.

Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.

Example

The static modifier is used to create class methods and variables, as in the following example:

public class InstanceCounter {

    private static int numInstances = 0;

    protected static int getCount() {

        return numInstances;

    }

    private static void addInstance() {

        numInstances++;

    }

    InstanceCounter() {

        InstanceCounter.addInstance();

    }

    public static void main(String[] arguments) {

        System.out.println(“Starting with ” +

                InstanceCounter.getCount() + ” instances”);

        for (int i = 0; i < 500; ++i) {

            new InstanceCounter();

        }

        System.out.println(“Created ” +

                InstanceCounter.getCount() + ” instances”);

    }

}

This will produce the following result:

Started with 0 instances

Created 500 instances

The Final Modifier

Final Variables

A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to an different object.

However, the data within the object can be changed. So, the state of the object can be changed but not the reference.

With variables, the final modifier often is used with static to make the constant a class variable.

Example

public class Test {

    final int value = 10;

    // The following are examples of declaring constants:

    public static final int BOXWIDTH = 6;

    static final String TITLE = “Manager”;

    public void changeValue() {

        value = 12; // will give an error

    }

}

Final Methods

A final method cannot be overridden by any subclasses. As mentioned previously, the final modifier prevents a method from being modified in a subclass.

The main intention of making a method final would be that the content of the method should not be changed by any outsider.

Example

You declare methods using the final modifier in the class declaration, as in the following example:

public class Test{

public final void changeName(){

        // body of method

        }

}

Final Classes

The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class.

Example

public final class Test {

        // body of class

}

Arrays Revisited

Arrays were introduced earlier, before classes had been discussed. Now that you know about

classes, an important point can be made about arrays: they are implemented as objects. Because

of this, there is a special array attribute that you will want to take advantage of. Specifically, the

size of an array—that is, the number of elements that an array can hold—is found in its length

instance variable. All arrays have this variable, and it will always hold the size of the array.

// This program demonstrates the length array member.

class Length {

    public static void main(String args[]) {

        int al[] = new int[10];

        int a2[] = { 3, 5, 7, 1, 8, 99, 44, -10 };

        int a3[] = { 4, 3, 2, 1 };

        System.out.println(“length of a1 is” + al.length);

        System.out.println(“length of a2 is” + a2.length);

        System.out.println(“length of a3 is” + a3.length);

    }

}

Output:

length of a1 is 10

length of a2 is 8

length of a3 is 4

Nested Classes

In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class.

Syntax:

Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class and the class Inner_Demo is the nested class.

class Outer_Demo {

        class Inner_Demo {

        }

}

Nested classes are divided into two types −

Inner Classes (Non-static Nested Classes)

Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class.

Inner classes are of three types depending on how and where you define them. They are −

Inner Class

Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.

Following is the program to create an inner class and access it. In the given example, we make the inner class private and access the class through a method.

Example

class Outer_Demo {

   int num;

   // inner class

   private class Inner_Demo {

      public void print() {

         System.out.println(“This is an inner class”);

      }

   }

   // Accessing he inner class from the method within

   void display_Inner() {

      Inner_Demo inner = new Inner_Demo();

      inner.print();

   }

}

public class My_class {

   public static void main(String args[]) {

      // Instantiating the outer class

      Outer_Demo outer = new Outer_Demo();

      // Accessing the display_Inner() method.

      outer.display_Inner();

   }

}

Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner class, display_Inner() is the method inside which we are instantiating the inner class, and this method is invoked from the main method.

If you compile and execute the above program, you will get the following result –

Output

This is an inner class.

Method-local Inner Class

In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method.

A method-local inner class can be instantiated only within the method where the inner class is defined. The following program shows how to use a method-local inner class.

Example

public class Outerclass {

   // instance method of the outer class

   void my_Method() {

      int num = 23;

      // method-local inner class

      class MethodInner_Demo {

         public void print() {

            System.out.println(“This is method inner class “+num);       

         }  

      } // end of inner class

      // Accessing the inner class

      MethodInner_Demo inner = new MethodInner_Demo();

      inner.print();

   }

   public static void main(String args[]) {

      Outerclass outer = new Outerclass();

      outer.my_Method();                    

   }

}

If you compile and execute the above program, you will get the following result −

Output

This is method inner class 23

Anonymous Inner Class

An inner class declared without a class name is known as an anonymous inner class. In case of anonymous inner classes, we declare and instantiate them at the same time. Generally, they are used whenever you need to override the method of a class or an interface. The syntax of an anonymous inner class is as follows −

Syntax

AnonymousInner an_inner = new AnonymousInner() {

public void my_method() {

……..

……..

}

};

The following program shows how to override the method of a class using anonymous inner class.

Example

 Live Demo

abstract class AnonymousInner {

   public abstract void mymethod();

}

public class Outer_class {

   public static void main(String args[]) {

      AnonymousInner inner = new AnonymousInner() {

         public void mymethod() {

            System.out.println(“This is an example of anonymous inner class”);

         }

      };

      inner.mymethod(); 

   }

}

If you compile and execute the above program, you will get the following result −

Output

This is an example of anonymous inner class

String Class

Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings

The most direct way to create a string is to write:

String greeting = “Hello world!”;

Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, “Hello world!’.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.

public class StringDemo{

public static void main(String args[]){

char[] helloArray = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘.’};

String helloString = new String(helloArray);

System.out.println( helloString );

        }

}

This will produce the following result:

hello.

Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes.

String Length

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.

The following program is an example of length(), method String class.

Example

 Live Demo

public class StringDemo {

   public static void main(String args[]) {

      String palindrome = “Dot saw I was Tod”;

      int len = palindrome.length();

      System.out.println( “String Length is : ” + len );

   }

}

This will produce the following result −

Output

String Length is : 17

Concatenating Strings

The String class includes a method for concatenating two strings −

string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in −

“My name is “.concat(“Zara”);

Strings are more commonly concatenated with the + operator, as in −

“Hello,” + ” world” + “!”

which results in −

“Hello, world!”

Let us look at the following example −

Example

 Live Demo

public class StringDemo {

   public static void main(String args[]) {

      String string1 = “saw I was “;

      System.out.println(“Dot ” + string1 + “Tod”);

   }

}

This will produce the following result −

Output

Dot saw I was Tod

Java Command Line Arguments

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

In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one argument from the command prompt.

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 

Output: Your first argument is: sonoo

Example of command-line argument that prints all the values

In this example, we are printing all the arguments passed from the command-line. For this purpose, we have traversed the array using for loop.

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 

Output: sonoo

       jaiswal

       1

       3

       abc

Variable Argument (Varargs):

The varrags allows the method to accept zero or muliple arguments. Before varargs either we use overloaded method or take an array as the method parameter but it was not considered good because it leads to the maintenance problem. If we don’t know how many argument we will have to pass in the method, varargs is the better approach.

Advantage of Varargs:

Syntax of varargs:

The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:

        return_type method_name(data_type… variableName){} 

Simple Example of Varargs in java:

class VarargsExample1{ 

 static void display(String… values){ 

  System.out.println(“display method invoked “); 

 } 

 public static void main(String args[]){ 

 display();//zero argument  

 display(“my”,”name”,”is”,”varargs”);//four arguments 

 }  

Output: display method invoked

       display method invoked

Another Program of Varargs in java:

class VarargsExample2{ 

 static void display(String… values){ 

  System.out.println(“display method invoked “); 

  for(String s:values){ 

   System.out.println(s); 

  } 

 } 

 public static void main(String args[]){ 

 display();//zero argument  

 display(“hello”);//one argument  

 display(“my”,”name”,”is”,”varargs”);//four arguments 

 }  

      Output:display method invoked

       display method invoked

       hello

       display method invoked

       my

       name

       is

       varargs

Rules for varargs:

While using the varargs, you must follow some rules otherwise program code won’t compile. The rules are as follows:

Overloading Varargs Methods

Similar to typical methods, you can overload a vararg methods. For example,

Before you learn about overloading vararg methods, make sure to learn about Java Method Overloading first.

class VarargOverload {

    private void test(int … args){

        int sum = 0;

        for (int i: args) {

            sum += i;

        }

        System.out.println(“sum = ” + sum);

    }

    private void test(boolean p, String … args){

        boolean negate = !p;

        System.out.println(“negate = ” + negate);

        System.out.println(“args.length = “+ args.length);

    }

    public static void main( String[] args ) {

        VarargOverload obj = new VarargOverload();

        obj.test(1, 2, 3);

        obj.test(true, “hello”, “world”);

    }

}

Output:

sum = 6

negate = false

args.length = 2

In the above program, test() method is overloaded by changing the number of arguments it accepts.

Varargs and Ambiguity

Somewhat unexpected errors can result when overloading a method that takes a variable length argument. These errors involve ambiguity because it is possible to create an ambiguous call to an overloaded varargs method. These errors involve ambiguity because both the methods are valid candidates for invocation. The compiler cannot decide onto which method to bind the method call.

Also, Read

  1. Unit-1 Java’s Lineage
  2. Unit-3 Data types, Variables, and Array
  3. Unit-4 Operator
  4. Unit-5 Control Statements
  5. Unit-6 Introducing Classes

Leave a Reply

Your email address will not be published. Required fields are marked *