0% found this document useful (0 votes)
21 views52 pages

Class Package

This document discusses method overloading in Java. It explains that method overloading occurs when a class has multiple methods with the same name but different parameters. There are two ways to overload methods in Java: 1) by changing the number of arguments and 2) by changing the data type of the arguments. The document provides examples of method overloading using both of these techniques. It also notes that method overloading is not possible by changing just the return type in Java.

Uploaded by

kaminisarode1507
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)
21 views52 pages

Class Package

This document discusses method overloading in Java. It explains that method overloading occurs when a class has multiple methods with the same name but different parameters. There are two ways to overload methods in Java: 1) by changing the number of arguments and 2) by changing the data type of the arguments. The document provides examples of method overloading using both of these techniques. It also notes that method overloading is not possible by changing just the return type in Java.

Uploaded by

kaminisarode1507
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/ 52

CHP 2 CLASS, OBJECT,

PACKAGES AND
INPUT/OUTPUT
By Dr. Megha V Gupta, NHITM
public class Example
{
//main method declaration
public static void main(String[] args)
{
System.out.println("hello world");
}
}

• PUBLIC CLASS EXAMPLE


THIS CREATES A CLASS CALLED EXAMPLE. YOU SHOULD MAKE SURE THAT THE CLASS NAME
STARTS WITH A CAPITAL LETTER, AND THE PUBLIC WORD MEANS IT IS ACCESSIBLE FROM
ANY OTHER CLASSES.
• PUBLIC STATIC VOID MAIN
• WHEN THE MAIN METHOD IS DECLARED PUBLIC, IT MEANS THAT IT CAN BE USED
OUTSIDE OF THIS CLASS AS WELL.
• THE WORD STATIC MEANS THAT WE WANT TO ACCESS A METHOD WITHOUT MAKING ITS
OBJECTS. AS WE CALL THE MAIN METHOD WITHOUT CREATING ANY OBJECTS.
• THE WORD VOID INDICATES THAT IT DOES NOT RETURN ANY VALUE. THE MAIN IS
DECLARED AS VOID BECAUSE IT DOES NOT RETURN ANY VALUE.
• MAIN IS THE METHOD, WHICH IS AN ESSENTIAL PART OF ANY JAVA PROGRAM.
public class Example
{
//main method declaration
public static void main(String[] args)
{
System.out.println("hello world");
}
}

• STRING[] ARGS
IT IS AN ARRAY WHERE EACH ELEMENT IS A STRING, WHICH IS NAMED AS ARGS. IF YOU
RUN THE JAVA CODE THROUGH A CONSOLE, YOU CAN PASS THE INPUT PARAMETER. THE
MAIN() TAKES IT AS AN INPUT.
• SYSTEM.OUT.PRINTLN();
THE STATEMENT IS USED TO PRINT THE OUTPUT ON THE SCREEN WHERE THE SYSTEM IS A
PREDEFINED CLASS, OUT IS AN OBJECT OF THE PRINTWRITER CLASS. THE METHOD
PRINTLN PRINTS THE TEXT ON THE SCREEN WITH A NEW LINE. ALL JAVA STATEMENTS END
WITH A SEMICOLON.
THE REQUIREMENT FOR JAVA HELLO WORLD EXAMPLE

• INSTALL THE JDK IF YOU DON'T HAVE INSTALLED IT, DOWNLOAD THE
JDK AND INSTALL IT.
• SET PATH OF THE JDK/BIN DIRECTORY.
• CREATE THE JAVA PROGRAM
• COMPILE AND RUN THE JAVA PROGRAM
CREATING HELLO WORLD EXAMPLE

CLASS SIMPLE
{
PUBLIC STATIC VOID MAIN(STRING ARGS[])
{
SYSTEM.OUT.PRINTLN("HELLO JAVA");
}
}
To compile: javac Simple.java Output:Hello Java

To execute: java Simple


IMPLEMENTING A JAVA
PROGRAM

COMPILING A JAVA PROGRAM:


✓ TO COMPILE A JAVA PROGRAM, EXECUTE THE JAVA COMPILER JAVAC, SPECIFYING THE
NAME OF THE SOURCE FILE ON THE COMMAND LINE. C:\> JAVAC EXAMPLE.JAVA
✓ WHEN JAVA SOURCE CODE IS COMPILED, EACH INDIVIDUAL CLASS IS PUT INTO IT’S OWN
OUTPUT FILE NAMED AFTER THE CLASS AND USING THE .CLASS EXTENSION.
✓ EACH FILE WITH .CLASS EXTENSION CONTAINS THE BYTECODE CORRESPONDING TO
THAT CLASS

6
IMPLEMENTING A JAVA PROGRAM

✓TO RUN THE PROGRAM, INTERPRETER JAVA IS USED THE NAME OF THE
CLASS THAT CONTAINS THE MAIN FUNCTION.
C:\> JAVA EXAMPLE
✓ACTUALLY IT SEARCHES FOR EXAMPLE. CLASS FILE.

7
METHOD IN JAVA

▪ A METHOD IS A BLOCK OF CODE WHICH ONLY RUNS WHEN IT IS CALLED.

⚫ YOU CAN PASS DATA, KNOWN AS PARAMETERS, INTO A METHOD.

⚫ METHODS ARE USED TO PERFORM CERTAIN ACTIONS, AND THEY ARE ALSO
KNOWN AS FUNCTIONS.

⚫ WHY USE METHODS? TO REUSE CODE: DEFINE THE CODE ONCE, AND USE
IT MANY TIMES.
CALL METHOD MULTIPLE TIMES
public class vehicle
{
static void car()
{
System.out.println("my car is swift!");
}

public static void main(String[] args)


{
//OUTPUT
car();
//My car is Swift!
car();
// My car is Swift!
car();
// My car is Swift!
}
}
EXAMPLE
public class vehicle
{
static void car(String fname)
{
System.out.println(" my car is " + fname);
}
public static void main(String[] args)
{
car("swift"); //OUTPUT

car("bmw"); //My car is Swift!

car("honda city"); // My car is BMW!

} // My car is Honda City!

}
METHOD WITH PARAMETER

• INFORMATION CAN BE PASSED TO FUNCTIONS AS PARAMETER.


PARAMETERS ACT AS VARIABLES INSIDE THE METHOD.

⚫ PARAMETERS ARE SPECIFIED AFTER THE METHOD NAME, INSIDE THE


PARENTHESES. YOU CAN ADD AS MANY PARAMETERS AS YOU WANT, JUST
SEPARATE THEM WITH A COMMA.
METHOD WITH RETURN VALUES

▪ THE VOID KEYWORD, USED IN THE EXAMPLES ABOVE, INDICATES THAT


THE METHOD SHOULD NOT RETURN A VALUE.
▪ IF YOU WANT THE METHOD TO RETURN A VALUE, YOU CAN USE A
PRIMITIVE DATA TYPE (SUCH AS INT, CHAR, ETC.) INSTEAD OF VOID, AND
USE THE RETURN KEYWORD INSIDE THE METHOD:
EXAMPLE RETURNS THE SUM OF A METHOD'S TWO PARAMETERS:

public class maths


{
static int add(int x, int y)
{
return x + y;
}

public static void main(String[] args)


{
System.out.println(add(5, 3));
}
}
// OUTPUTS 8
JAVA - CONSTRUCTORS
• A constructor initializes an object when it is created. It has the same name as its class
and is syntactically similar to a method. However, constructors have no explicit return
type.

● Typically, you will use a constructor to give initial values to the instance variables
defined by the class, or to perform any other start-up procedures required to create a
fully formed object.

● All classes have constructors, whether you define one or not, because java automatically
provides a default constructor that initializes all member variables to zero. However,
once you define your own constructor, the default constructor is no longer used.
SYNTAX

● FOLLOWING IS THE SYNTAX OF A CONSTRUCTOR −

class classname
{
classname()
{
}
}
TYPES OF CONSTRUCTORS

JAVA ALLOWS TWO TYPES OF CONSTRUCTORS


NAMELY −

● NO ARGUMENT CONSTRUCTORS
● PARAMETERIZED CONSTRUCTORS
NO ARGUMENT CONSTRUCTORS

● As the name specifies the no argument constructors of java does not


accept any parameters instead, using these constructors the instance
variables of a method will be initialized with fixed values for all
objects.
EXAMPLE
class myclass
{
int num;
myclass()
{
num = 100; OUTPUT:
} 100 100
}
class consdemo
{
public static void main(String args[])
{
myclass t1 = new myclass();
myclass t2 = new myclass();
System.out.println(t1.num + " " + t2.num);
}
}
PARAMETERIZED CONSTRUCTORS

● Most often, you will need a constructor that accepts one or more
parameters.
● Parameters are added to a constructor in the same way that they are
added to a method, just declare them inside the parentheses after the
constructor's name.
EXAMPLE
// a simple constructor.
class myclass
{
int x;
myclass(int i )
{
x = i;
} OUTPUT:
} 10 20
class consdemo
{
public static void main(String args[])
{
myclass t1 = new myclass( 10 );
myclass t2 = new myclass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
WHAT IS METHOD OVERLOADING?

• IF A CLASS HAVE MULTIPLE METHODS BY SAME NAME BUT DIFFERENT 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.
ADVANTAGE OF METHOD OVERLOADING?

• METHOD OVERLOADING INCREASES THE READABILITY OF THE PROGRAM.


DIFFERENT WAYS TO OVERLOAD THE METHOD

THERE ARE TWO WAYS TO OVERLOAD THE METHOD IN JAVA


• BY CHANGING NUMBER OF ARGUMENTS
• BY CHANGING THE DATA TYPE

NOTE: IN JAVA, METHOD OVERLOADING IS NOT POSSIBLE BY CHANGING THE RETURN TYPE OF
THE METHOD.
1. METHOD OVERLOADING BY
CHANGING THE NO. OF ARGUMENTS
class Calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Output:
Calculation obj=new Calculation();
30
obj.sum(10,10,10);
40
obj.sum(20,20);
}
}
2)METHOD OVERLOADING BY
CHANGING DATA TYPE OF ARGUMENT
class Calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}
public static void main(String args[]) Output:
{ 21.0
Calculation obj=new Calculation(); 40
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
WHY METHOD OVERLOADING IS NOT POSSIBLE BY
CHANGING THE RETURN TYPE OF METHOD?
class Calculation
{
int sum(int a,int b)
{
System.out.println(a+b);
}
double sum(int a,int b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Calculation obj=new Calculation();
int result=obj.sum(20,20);
//Compile Time Error
/* Here how can java determine which sum() method should be called */
}
}
// Java program to demonstrate working of method // Driver code
// overloading in Java. public static void main(String args[])
{
public class Sum Sum s = new Sum();
{ System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
// Overloaded sum(). This sum takes two int parameters System.out.println(s.sum(10.5, 20.5));
public int sum(int x, int y) }
{ }
return (x + y);
}

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double parameters


public double sum(double x, double y)
{
return (x + y);
}
// Constructor Overloading // Driver code
class Box public class Test
{ {
double width, height, depth; public static void main(String args[])
{
// constructor used when all dimensions specified // create boxes using the various constructors
Box(double w, double h, double d) Box mybox1 = new Box(10, 20, 15);
{ Box mybox2 = new Box();
width = w; Box mycube = new Box(7);
height = h;
depth = d; double vol;
}
// constructor used when no dimensions specified // get volume of first box
Box() vol = mybox1.volume();
{ System.out.println(" Volume of mybox1 is " + vol);
width = height = depth = 0;
} // get volume of second box
// constructor used when cube is created vol = mybox2.volume();
Box(double len) System.out.println(" Volume of mybox2 is " + vol);
{
width = height = depth = len; // get volume of cube
} vol = mycube.volume();
// compute and return volume System.out.println(" Volume of mycube is " + vol);
double volume() }
{ }
return width * height * depth;
}
}
ACCESS MODIFIERS IN JAVA
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.
UNDERSTANDING JAVA ACCESS MODIFIERS

Access Modifier within class within package outside outside


package by package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Result unit
• INPUT AND OUTPUT FUNCTIONS IN JAVA ( ALREADY COVERED IN THE CLASS)
• BUFFERED READER CLASS, SCANNER CLASS (ALREADY COVERED IN THE CLASS ALONG WITH
PROGRAMS)

You might also like