0% found this document useful (0 votes)
41 views12 pages

EWIT OOJmodule2pdf

Uploaded by

shadow.range03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views12 pages

EWIT OOJmodule2pdf

Uploaded by

shadow.range03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Overloading methods

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand the
behavior of the method because its name differs.

Simple example that illustrates method overloading


Class OverloadDemo{
void test(){
System.out.println(“No parameters”);
}
void test(int a){
System.out.println(“a:” +a);
}
void test(int a, int b){
system.out.println(“a and b: “+a+ “ ” +b);
}
Class overlad{
Public static void main(String[] args){
OverloadDemo ob =new OverloadDemo();
ob.test();
ob.test(10);
ob.test(10,20);
}
}

Overloading Constructors
In Java, we can overload constructors like methods. 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.
Class Box{
double width;
double height;
double depth;
Box(double w, double h, double d){
width=w;
height=h;
depth=d;
}
Box( ){
width=-1;
height=-1;
depth=-1;
}
Box( double len){
width=height=depth=len;
}
Double volume( ){
return width*height*depth;
}
}
Class OverloadCons{
Public static void main (String[] args){
Box mybox1=new Box(10,20,15);
Box mybox2=new Box();
Box mycube=new Box(7);
Double vol;
vol=mybox1.volume();
System.out.println(“Volume of mybox1 is” +vol);
vol=mybox2.volume();
System.out.println(“volume of mybox2 is” +vol);
vol=mucube.volume();
system.out.println(“volume of mycube is”+ vol);
}
}

Using objects as parameters


Objects, like primitive types, can be passed as parameters to methods in Java. When passing an
object as a parameter to a method, a reference to the object is passed rather than a copy of the
object itself. This means that any modifications made to the object within the method will have
an impact on the original object.
Class Test{
Int a,b;
Test(int i, int j)
a = i;
b = j;
}
boolean equalTo(Test o){
If(o.a == a && o.b ==b)
return true;
else return false;
}
}
Class passOb{
Public static void main(String[] args){
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100,22);
Test ob3 = new Test(-1, -1);
System.out.println(“ob1 == ob2: “ + ob1.equalTo(ob2));
System.out.println(“ob1 == ob3: “ + ob1.equalTo(ob3));
}
}

Argument passing

Parameter passing in Java refers to the mechanism of transferring data between methods or
functions. Java supports two types of parameters passing techniques

1. Call-by-value
2. Call-by-reference.

Types of Parameters:

1. Formal Parameter:

A variable and its corresponding data type are referred to as formal parameters when they exist
in the definition or prototype of a function or method. As soon as the function or method is
called and it serves as a placeholder for an argument that will be supplied. The function or
method performs calculations or actions using the formal parameter.

syntax
returnType functionName(dataType parameterName)
{
// Function body
// Use the parameterName within the function
}

In the above syntax:

o returnType represents the return type of the function.


o functionName represents the name of the function.
o dataType represents the data type of the formal parameter.
o parameterName represents the name of the formal parameter.

2. Actual Parameter:

The value or expression that corresponds to a formal parameter and is supplied to a function or
method during a function or method call is referred to as an actual parameter is also known as an
argument. It offers the real information or value that the method or function will work with.

Syntax:

functionName(argument)
In the above syntax:

o functionName represents the name of the function or method.


o argument represents the actual value or expression being passed as an argument to the
function or method.

1. Call-by-Value:

In Call-by-value the copy of the value of the actual parameter is passed to the formal parameter
of the method. Any of the modifications made to the formal parameter within the method do not
affect the actual parameter.

import java.util.*;
public class CallByValueExample
{
public static void main(String[] args)
{
int num = 10;
System.out.println("Before calling method:"+num);
modifyValue(num);
System.out.println("After calling method:"+num);
}

public static void modifyValue(int value) {

// Modifying the formal parameter


value=20;
System.out.println("Inside method:"+value);
}
}

Call-by-Reference:

Call by reference" is a method of passing arguments to functions or methods where the memory
address (or reference) of the variable is passed rather than the value itself. This means that
changes made to the formal parameter within the function affect the actual parameter in the
calling environment.

In "call by reference," when a reference to a variable is passed, any modifications made to the
parameter inside the function are transmitted back to the caller. This is because the formal
parameter receives a reference (or pointer) to the actual data.

import java.util.*;

class CallByReference
{
int a,b;

CallByReference(int x,int y)
{
a=x;
b=y;
}

// Method to change the values of class variables


void changeValue(CallByReference obj)
{
obj.a+=10;
obj.b+=20;
}
}

public class CallByReferenceExample


{
public static void main(String[] args)
{

CallByReference object=new CallByReference(10, 20);

System.out.println("Value of a: "+object.a +" & b: " +object.b);


object.changeValue(object);
System.out.println("Value of a:"+object.a+ " & b: "+object.b);
}
}

Returning objects

A method can return any type of data, including class types that user create. For example, in the
following program, the incrByTen( ) method returns an object in which the value of a is te
greater than it is in the invoking object.

class Test{
int a;
Test (int i){
a=i;
}
Test incrByten( ){
Test temp = new Test (a+10);
return temp;
}
}
class RetOb{
Public static void main (String[] args){
Test ob1=new Test(2);
Test ob2;
Ob2 = ob1.incrByTen( );
System.out.println(“ob1.a: “ + ob1.a);
System.out.println(“ob2.a: “ + ob2.a);
Ob2 = ob2.incrByTen();
System.out.println(“on2. After second increase:” + ob2.a);
}
}

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.

Syntax:

returntype methodname(){
//code to be executed
methodname();//calling same method
}

Example: Factorial number


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

Access Control

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

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
}
}

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.
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

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

Java 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 keyword belongs to the
class than an instance of the class.

Example of static variable

class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
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");
//we can change the college of all objects by the single line of code
//Student.college="EWITY";
s1.display();
s2.display();
}
}

Output:

111 Karan ITS

222 Aryan ITS


Final keyword

The final keyword is a non-access modifier used for classes, attributes and methods, which
makes them non-changeable (impossible to inherit or override).

public class Main {

final int x = 10;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 25; // will generate an error: cannot assign a value to a final variable

System.out.println(myObj.x);

Java inner class and nested class

A class inside another class, that class is known as a java nested class. The class that contains
the other class is known as the outer class and the contained class is known as inner class. The
concept of nested class was introduced to achieve logical grouping of classes and provide
more encapsulation.

OuterClass
{
// Body of OuterClass
InnerClass
{
/// Body of InnerClass
}
}
We have two categories of nested classes, ie. Static nested class and non-static nested
class(inner classes). We don’t use static keyword with Inner classes..
class OuterClass
{
// Body of OuterClass
static class StaticNestedClass
{
// Body of StaticNestedClass
}
class InnerClass
{
// Body of OuterClass
}
}

You might also like