0% found this document useful (0 votes)
22 views23 pages

Java M2

The document introduces the fundamentals of classes in Java, explaining the structure and components of a class, including fields, methods, and constructors. It covers object creation, method overloading, and the use of the 'this' keyword, as well as garbage collection and memory management. Additionally, it discusses passing objects as parameters, argument passing techniques, and recursion in Java programming.

Uploaded by

w7776035
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)
22 views23 pages

Java M2

The document introduces the fundamentals of classes in Java, explaining the structure and components of a class, including fields, methods, and constructors. It covers object creation, method overloading, and the use of the 'this' keyword, as well as garbage collection and memory management. Additionally, it discusses passing objects as parameters, argument passing techniques, and recursion in Java programming.

Uploaded by

w7776035
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

Module-2

INTRODUCING CLASSES
CLASS FUNDAMENTALS
• In object-oriented programming technique, a program is designed using objects and
classes.

• A class

• Core of oop and java

• Defines shape and nature of an object

• Defines a new datatype, once defined it can be used to create objects of that
type.

• Thus class is template, an object is an instance of a class.

• A class in Java is a logical entity only.

• Any concept you wish to implement in a Java program must be encapsulated within a
class.

• Simple pgms done so far was to encapsulate the main method.

➢ A class in Java can contain:

• Fields

• Methods

• Constructors

• Blocks

• Nested class and interface


The General Form of a Class

• A simplified general form of a class definition is

class classname {

type instance-variable1;

type instance-variable2;

// ... type instance-variableN;


type methodname1(parameter-list) {

// body of method

type methodname2 (parameter-list) {

// body of method

// ... type methodnameN(parameter-list) {

// body of method

Syntax to declare a class:

class <class_name>{

field;

method; }

➢ To define a class

• Specify data it contains and

• Code that operates on that data

-defines interface to its data

-determines how class’ data can be used

A class is declared by use of the class keyword

Example:
➢ To actually create a Box object, you will use a statement like the following:

Box mybox = new Box(); // create a Box object called mybox

DECLARING OBJECTS
• The new keyword is used to allocate memory at runtime.
• All objects get memory in Heap memory area.

Example:

Box b1 = new Box();


Box b2 = b1;

• b2 is being assigned a reference to a copy of the object referred to by b1.


• b1 and b2 refer to separate and distinct objects. However, this would be wrong. Instead,
after this fragment executes, b1 and b2 will both refer to the same object.

INTRODUCING METHODS
• A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation.
• It is used to achieve the reusability of code.
• Methods define the interface to most classes.
• This allows the class implementer to hide the specific layout of internal data structures.
• Methods are defined to provide access to data
• General form of a method:
type name(parameter-list) {
// body of method
}
Here, type specifies the type of data returned by the method.
• If the method does not return a value, its return type must be void.
• The name of the method is specified by name.
• The parameter-list is a sequence of type and identifier pairs separated by commas.
• Methods that have a return type other than void return a value to the calling routine
using the following form of the return statement:

return value;

Here, value is the value returned.


Example:
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){[Link](rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
[Link](111,"Karan");
[Link](222,"Aryan");
[Link]();
[Link]();
}
}
CONSTRUCTORS
• A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set initial
values for object attributes.
• Tedious to initialize all of the variables in a class each time an instance is created.
• Thus automatic initialization done with use of a constructor.
• A constructor initializes an object immediately upon creation.
• Every time an object is created using the new() keyword, at least one constructor is
called.
• Java compiler provides a default constructor by default, if no constructor available in
the class.
• The constructor is automatically called immediately after the object is created, before
the new operator completes.
• Constructors have no return type, not even void.
• This is because the implicit return type of a class’ constructor is the class type
itself.

Types of Java constructors

o Default constructor (no-arg constructor)


o Parameterized constructor
• A constructor without any parameters.
class Student3{
int id;
String name;
//method to display the value of id and name
void display(){ [Link](id+" "+name);
}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
[Link]();
[Link]();
}
}
Parameterized Constructors
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(){[Link](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
[Link]();
[Link]();
}
this KEYWORD
-In java, this is a reference variable that refers to the current object.
-Sometimes a method will need to refer to the object that invoked it.
To allow this, Java defines the this keyword.
-this can be used inside any method to refer to the current object.

//A redundant use of this.


Box(double width, double height, double depth)
{
[Link] = width;
[Link] = height;
[Link] = depth;
}
Instance Variable Hiding
• It is illegal in Java to declare two local variables with the same name inside the same
or enclosing scopes.
• However, when a local variable has the same name as an instance variable, the local
variable hides the instance variable.
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
[Link] = width;
[Link] = height;
[Link] = depth;
}
GARBAGE COLLECTION
• Garbage collection in Java is the process by which Java programs perform automatic
memory management.
• When Java programs run on the JVM, objects are created on the heap, which is a
portion of memory dedicated to the program. Eventually, some objects will no
longer be needed. The garbage collector finds these unused objects and deletes them
to free up memory.
Module-2

Methods and Classes: Overloading Methods, Objects as Parameters, Argument Passing, Returning
Objects, Recursion, Access Control, Understanding static, Introducing final, Introducing Nested and
Inner Classes

CHAPTER 2:
METHODS AND CLASSES
OVERLOADING METHODS
• In Java, it is possible to define two or more
methods within the same class that share the same name, as
long as their parameter declarations are different. When this is
the case, the methods are said to be overloaded, and the
processis referred to as method overloading
• If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
• Method overloading is one of the ways that Java supports
polymorphism.

• In java, method overloading is not possible by changing the return type of the method only
because of ambiguity.
• There are two ways to overload the method in java

By changing number of arguments


By changing the data type

1. Method Overloading: changing no. of arguments

In this example, we have created two methods, first add () method performs addition of two
numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for
calling methods.

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{

Dept of CSE KSIT [Link]


Module-2

public static void main(String[] args){

[Link]([Link](11,11));

[Link]([Link](11,11,11));

}}

Output:

22
33

2. Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double 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){

[Link]([Link](11,11));

[Link]([Link](12.3,12.6));

}}

Output:

22
24.9

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.

Dept of CSE KSIT [Link]


Module-2

public class Student {

//instance variables of the class

int id;

String name;

Student(){

[Link]("this a default constructor");

Student(int i, String n){

id = i;

name = n;

public static void main(String[] args) {

//object creation

Student s = new Student();

[Link]("\nDefault Constructor values: \n");

[Link]("Student Id : "+[Link] + "\nStudent Name : "+[Link]);

[Link]("\nParameterized Constructor values: \n");

Student student = new Student(10, "David");

[Link]("Student Id : "+[Link] + "\nStudent Name : "+[Link]);

USING OBJECTS AS PARAMETERS

Dept of CSE KSIT [Link]


Module-2

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.

public class MyClass {


private int attribute1;
private String attribute2;
private double attribute3;

// Constructor
public MyClass(int attribute1, String attribute2, double attribute3) {
this.attribute1 = attribute1;
this.attribute2 = attribute2;
this.attribute3 = attribute3;
}

// Method with object as parameter


public void myMethod(MyClass obj) {
[Link]("Attribute 1: " + obj.attribute1);
[Link]("Attribute 2: " + obj.attribute2);
[Link]("Attribute 3: " + obj.attribute3);
}

public static void main(String[] args) {


MyClass myObject1 = new MyClass(10, "Hello", 3.14);
MyClass myObject2 = new MyClass(20, "World", 6.28);

// Call the method with object as parameter


[Link](myObject2);
}
}

An object belonging to the "MyClass" class is used as a parameter in the myMethod()


function. This enables the method to operate on the passed object and access its attributes and
methods.

ARGUMENT PASSING

Dept of CSE KSIT [Link]


Module-2

• Arguments in Java are always passed-by-value. During method invocation, a copy of


each argument, whether it’s a value or reference, is created in stack memory which is
then passed to the method.
• In general, there are two ways that a computer language
can pass an argument to a subroutine. The first
way is call-by value. This approach 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.
• Object references can be parameters. Call by value is used, but now the value is an
object reference. This reference can be used to access the object and possibly change
it.
// Java program to illustrate Call by Value
// Callee
class CallByValue {

// Function to change the value


// of the parameters
public static void example(int x, int y)
{
x++;
y++;
}
}

// Caller
public class Main {
public static void main(String[] args)
{
int a = 10;
int b = 20;
// Instance of class is created
CallByValue object = new CallByValue();

[Link]("Value of a: " + a
+ " & b: " + b);
// Passing variables in the class function
[Link](a, b);

// Displaying values after


// calling the function

Dept of CSE KSIT [Link]


Module-2

[Link]("Value of a: "+ a + " & b: " + b);


}
}

Value of a: 10 & b: 20
Value of a: 10 & b: 20
---------------------------------------------------------------------------------------------------------

// Java program to illustrate Call by Reference

// Callee
class CallByReference {

int a, b;

// Function to assign the value


// to the class variables
CallByReference(int x, int y)
{
a = x;
b = y;
}

// Changing the values of class variables


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

// Caller
public class Main {

public static void main(String[] args)


{

// Instance of class is created


// and value is assigned using constructor
CallByReference object
= new CallByReference(10, 20);

[Link]("Value of a: " + object.a

Dept of CSE KSIT [Link]


Module-2

+ " & b: " + object.b);

// Changing values in class function


[Link](object);

// Displaying values
// after calling the function
[Link]("Value of a: " + object.a
+ " & b: " + object.b);
}
}

Value of a: 10 & b: 20
Value of a: 20 & b: 40

RETURNING OBJECTS

A method can return any type of data, including class types.

For example, the class ErrorMsg shown here could be used to report errors. Its method,
getErrorMsg( ), returns a String object that contains a description of an error based upon the
error code that it is passed.

Dept of CSE KSIT [Link]


Module-2

RECURSION

Recursion is the technique of making a function call itself. This technique provides a way to
break complicated problems down into simple problems which are easier to solve.

Base Condition in Recursion

In the recursive program, the solution to the base case is provided and the solution to the
bigger problem is expressed in terms of smaller problems.

int fact(int n)

if (n < = 1) // base case

Dept of CSE KSIT [Link]


Module-2

return 1;

else

return n*fact(n-1);

Example:

// Java Program to implement

// Factorial using recursion

class GFG {

// recursive method

int fact(int n)

int result;

if (n == 1)

return 1;

result = fact(n - 1) * n;

return result;

class Recursion {

// Main function

public static void main(String[] args)

GFG f = new GFG();

Dept of CSE KSIT [Link]


Module-2

[Link]("Factorial of 3 is "+ [Link](3));

[Link]("Factorial of 4 is "+ [Link](4));

[Link]("Factorial of 5 is "+ [Link](5));

• When a methodcalls itself, new local variables and parameters


are allocated storage on the stack, and the methodcode is
executed with these new variables from the start.
• The main advantage to recursive methods is that they
can be used to create clearer and simplerversions of several
algorithms than can their iterative relatives.

INTRODUCING ACCESS CONTROL

• Encapsulation links data with the code that manipulates it – thru Class and
object.
• Encapsulation provides another important attribute: access control.
• Through encapsulation, you can control
what parts of a program can access the members of a class.
• Thus can prevent misuse.
Eg: restricting data access only through a set of methods.
• Java’s access specifiers are
• public, private, and protected.
• Java also defines a default access level.
• protected applies only when inheritance is involved.
• Access modifiers in Java helps to restrict the scope of
• a class, constructor , variable , method or data member.
• There are four types of access modifiers available in java:
• Default – No keyword required
• Private
• Protected
• Public

Default Access Modifier


• When no access modifier is specified for a class, method, or data member – It
is said to be having the default access modifier by default.
• The data members, classes, or methods that are not declared using any access
modifiers i.e. having default access modifiers are accessible only within the
same package.

Dept of CSE KSIT [Link]


Module-2

// Java program to illustrate default modifier


package p1;

// Class Geek is having Default access modifier


class Geek
{
void display()
{
[Link]("Hello World!");
}
}
public:
• Specified using the keyword public.
• The public access modifier has the widest scope among all other access
modifiers.
• Classes, methods or data members which are declared as public are accessible
from every where in the program.
• There is no restriction on the scope of a public data members.

package p2;
import p1.*;
class B {
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
• Private:
• specified using the keyword private
• The methods or data members declared as private are accessible only within
the class in which they are declared.
• Any other class of same package will not be able to access these members.
• Top level Classes or interface can not be declared as private because
• private means “only visible within the enclosing class”.
• protected means “only visible within the enclosing class and any subclasses”
• Hence these modifiers in terms of application to classes, they apply only to
nested classes and not on top level classes.
// private modifier
package p1;

class A
{

Dept of CSE KSIT [Link]


Module-2

private void display()


{
[Link]("GeeksforGeeks");
}
}

class B
{
public static void main(String args[])
{
A obj = new A();
// Trying to access private method
// of another class
[Link]();
}
}
• protected:
• Specified using the keyword protected.
• The methods or data members declared as protected are accessible within same
package or sub classes in different package.

// protected modifier
package p2;
import p1.*; // importing all classes in package p1

// Class B is subclass of A
class B extends A
{
public static void main(String args[])
{
B obj = new B();
[Link]();
}

}
UNDERSTANDING STATIC
• Are the methods in Java that can be called without creating an object of class.
• They are referenced by the class name itself or reference to the Object of that class
• Static method(s) are associated to the class in which they reside i.e. they can be called
even without creating an instance of the class i.e [Link](args).
• They are designed with aim to be shared among all Objects created from the same
class.

Dept of CSE KSIT [Link]


Module-2

• Static methods cannot be overridden. But can be overloaded since they are resolved
using static binding by compiler at compile time.

Static Variables
Declared with static keyword, outside method but inside class.

All the static variables are allocated and initialized only once at the start of the
program.

Is independent of object of that class, only one instance is created which is shared by
every object of the class.

So memory consumption is very less.

Eg: variables that are common to all objects can be made static, like
• Interest rate in banking operations of specific type of accounts
e.g:
static int x;
int y;
are declared in a class and 10 objects are created.
10 instances of y will be created in the 10 objects i.e 40 bytes of memory.
This 40 byte memory is allocated from stack segment.
• And only 1 instance of x is created i.e 4 bytes of memory, which is shared by the 10
objects.
• So each object can modify it and the modified value will be reflected for other objects
[Link] 4 byte memory is allocated from data segment.

When a member is declared static,


It can be accessed before any objects of its class are created, and without reference to
any object.
You can declare both methods and variables to be static.
The most common example of a static member is main( ).
main( ) is declared as static because it must be called before any objects exist.
Example:
class VariableDemo {
static int count=0;

public void increment() {


count++;
}

public static void main(String args[]) {

VariableDemo obj1=new VariableDemo();

Dept of CSE KSIT [Link]


Module-2

VariableDemo obj2=new VariableDemo();


[Link]();
[Link]();

[Link]("Obj1: count is="+[Link]);


[Link]("Obj2: count is="+[Link]);
}
}
INTRODUCING FINAL
• A field can be declared as final. Doing so prevents
its contents from being modified, making it, essentially, a constant.
• This means that you must initialize a final field when it is
declared.
• You can do this in one of two ways:
• First, you can give it a value when it is declared.

• Second, you can assign it a value within a


constructor. The first approach is probably the most
common.
Here is an example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT =
• Declaring a parameter final prevents it from being
changed within the method. Declaring a local
variable final prevents it from being assigned a value more
than once.
INTRODUCING NESTED AND INNER CLASSES.
Defining a class within another class
To logically group classes that are only used in one place
-thus this increases the use of encapsulation, and create more readable and
maintainable code.
class OuterClass {
...
class NestedClass {
...
}
}

• A nested class that is declared directly within its enclosing class scope is a
member of its enclosing class.

Dept of CSE KSIT [Link]


Module-2

Eg: Class B is a member of class A

• It is also possible to declare a nested class that is local to a block.


• Two types of nested classes:
static and non-static.

• Scope of a nested class is bounded by the scope of its enclosing class.


• If class B is defined within class A, then scope of B is bounded by scope of A,
and B does not exist independently /without of A.[B not available outside A] .
• A nested class (B) has access to the members, including private members, of the
class in which it is nested (A).
• Eg: If B is a class defined inside class A, then B can access private members
of class A.
• The enclosing class does not have access to the members of the nested
class.
• Eg: Class A cannot access members of class B. [need to create object]
• A nested class that is declared directly within its enclosing class scope is a
member of its enclosing class.
• Eg: Class B is a member of class A
• It is also possible to declare a nested class that is local to a block.
• Two types of nested classes:
• static and non-static.
• Static classes- with static keyword
• A static class must access the members of its enclosing class through an object.
• it cannot refer to members of its enclosing class directly, so static nested classes
are seldom used.
Inner class
•An inner class is a non-static nested class.

It has access to all of the variables and methods of its outer class and may refer
to them directly.
• Eg: Refer pgm InnerClassDemo
• outer class has
• one instance variable named outer_x,
• one instance method named test( ),and
• defines one inner class called Inner.

class OuterClass
{
// static member
static int outer_x = 10;

// instance(non-static) member

Dept of CSE KSIT [Link]


Module-2

int outer_y = 20;

// private member
private static int outer_private = 30;

// static nested class


static class StaticNestedClass
{
void display()
{
// can access static member of outer class
[Link]("outer_x = " + outer_x);

// can access display private static member of outer class


[Link]("outer_private = " + outer_private);

Dept of CSE KSIT [Link]

You might also like