0% found this document useful (0 votes)
2 views70 pages

2.1 Java-Classes and Methods

The document outlines the principles of Java as an object-oriented programming language, covering key concepts such as objects, classes, methods, and constructors. It explains the relationship between classes and objects, the significance of attributes and operations, and details on method overloading and static members. Additionally, it provides examples of declaring objects, using constructors, and implementing methods with parameters.

Uploaded by

sanskariop79
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)
2 views70 pages

2.1 Java-Classes and Methods

The document outlines the principles of Java as an object-oriented programming language, covering key concepts such as objects, classes, methods, and constructors. It explains the relationship between classes and objects, the significance of attributes and operations, and details on method overloading and static members. Additionally, it provides examples of declaring objects, using constructors, and implementing methods with parameters.

Uploaded by

sanskariop79
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

Sub Code: 210255

Principles of Programming Languages

SE Computer Engineering
(2019 Pattern)
UNIT-III
Java as Object Oriented Programming
Language
Unit 3: Syllabus

 Fundamentals Of Java, Arrays: One Dimensional Array, Multi-


Dimensional Array, Alternative Array Declaration Statements,
 String Handling: String Class Methods,
 Classes And Methods: Class, Objects, Constructors, This Keyword,
Garbage Collection, Finalize() Method, Overloading Methods Argument
Passing, Object As Parameter, Returning Objects, Access Control, Static &
Final, Nested And Inner Classes, Command Line Arguments, Variable -
Length Arguments.
What is an Object ?

▪ Formally, an object is an entity with a well defined boundary and identity


that encapsulates its state & behavior
➢ State: is represented by attributes and relationships
➢ Behavior: is represented by operations, methods.
What is an Object ?

• Object Has State


➢ The state of an object is one of the possible conditions in which an
object may exist
➢ The state of an object normally changes over time
E.g. Kanetkar is an object of class Professor. The Kanetkar object has
state:
❑ Name=Kanetkar
❑ Employee Id=2001
❑ Hire date=02/02/1995
❑ Status=Tenured
❑ Max Load=3
What is an Object ?

• Object has Behavior


➢ Behavior determines how an object acts and reacts.
➢ The visible behavior of an object is modeled by the set of
messages it can respond to (operations the object can perform)

Professor Kanetkar’s Behavior :


❑ Submit Final Grades()

❑ Accept Course Offerings()

❑ Take a vacation()
What is an Object ?

➢ Object has Identity

Each object has a unique identity, even if the state is identical to that of
another object.

E.g. Professor Kanetkar is from Nagpur. Even if there is a professor


with the same name – Kanetkar in Pune teaching C++, they both
are distinct objects
What is a Class?

➢ A class is a description of a set of objects that share the

same attributes, operations.

➢ An object is an instance of class.

A class is an abstraction in that it


➢ Emphasizes relevant characteristics
➢ Suppresses other characteristics
A Relationship Between Classes & Objects

➢ A class is an abstract definition of an object.

➢ It defines the structure & behavior of each object in the


class

➢ It serves as a template / blue print for creating objects


A Relationship Between Classes
& Objects
• Attributes of a Class

➢ An attribute is a named property of a class that describes a range of


values that instances of the property may hold.

➢ A class may have any number of attributes or no attributes at all.

➢ An attribute has a type, which tells us what kind of attribute it is.

➢ Typically attributes are integer, boolean, varchar etc.

➢ These are called primitive types. Primitive types can be specific for a
certain programming language.
Operations of a Class

• An operation is the implementation of a service that can be requested


from any object of the class to affect behavior
➢ A class may have any number of operations or none at all.
➢ The operations in a class describe what class can do.
➢ The operation is described with a return-type, name, zero and more
parameters.
➢ This is know as signature of an operation.
➢ Often, but not always, invoking an operation on an object
changes the object’s data or state.
Declaring Objects

Box mybox = new Box();

This statement combines the two steps just described. It can be


rewritten like this to show each step more clearly

Box mybox; // declare reference to object


mybox = new Box(); // allocate a Box object
Declaring Objects
Assigning Object Reference
Variables
Box b1 = new Box();
Box b2 = b1;

➢ You might think that b2 is being assigned a reference to a copy of the object

referred to by b1. That is, you might think that 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.

➢ The assignment of b1 to b2 did not allocate any memory or copy any part of

the original object.


Assigning Object Reference
Variables

➢ It simply makes b2 refer to the same object as does b1.

➢ Thus, any changes made to the object through b2 will affect the object

to which b1 is referring, since they are the same object.


CLASSES & OBJECTS
CLASSES & OBJECTS
CLASSES & OBJECTS
CLASSES & OBJECTS
Introducing Methods

classes usually consist of two things: instance variables and methods.


This is the 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. This can be any legal identifier
other than those already used by other items within the current scope.
Introducing Methods

➢ The parameter-list is a sequence of type and identifier pairs separated by


commas. Parameters are essentially variables that receive the value of the
arguments passed to the method when it is called.

➢ 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


Adding a Method to the Box Class
// This program includes a method inside the box class.
class Box { / * assign values to mybox1's instance
double width; variables */
double height; [Link] = 10;
double depth; [Link] = 20;
// display volume of a box [Link] = 15;
void volume() { /* assign different values to mybox2's instance
[Link]("Volume is "); variables */
[Link](width * height * depth); [Link] = 3;
} [Link] = 6;
} [Link] = 9;
class BoxDemo3 { // display volume of first box
public static void main(String args[]) { [Link]();
Box mybox1 = new Box(); // display volume of second box
Box mybox2 = new Box(); [Link]();
} Output
Volume is 3000.0
Volume is 162.0
Returning a Value

// Program for Returning a Value // assign values to mybox1's instance variables


class Box { [Link] = 10;
double width; [Link] = 20;
double height; [Link] = 15;
double depth; /* assign different values to mybox2's
// compute and return volume instance variables */
double volume() { [Link] = 3;
return width * height * depth; [Link] = 6;
} [Link] = 9;
} // get volume of first box
class BoxDemo4 { vol = [Link]();
public static void main(String args[]) { [Link]("Volume is " + vol);
Box mybox1 = new Box(); // get volume of second box
Box mybox2 = new Box(); vol = [Link]();
double vol; [Link]("Volume is " + vol);
}
}

Output
Volume is 3000.0
Volume is 162.0
Adding a Method That Takes
Parameters
// This program uses a parameterized method.
class Box { class BoxDemo5 {
double width; public static void main(String args[]) {
double height; Box mybox1 = new Box();
double depth; Box mybox2 = new Box();
// compute and return volume double vol;
double volume() { // initialize each box
return width * height * depth; [Link](10, 20, 15);
} [Link](3, 6, 9);
// sets dimensions of box // get volume of first box
void setDim(double w, double h, double d) { vol = [Link]();
width = w; [Link]("Volume is " + vol);
height = h; // get volume of second box
depth = d; vol = [Link]();
} [Link]("Volume is " + vol);
} }
}
Output
Volume is 3000.0
Volume is 162.0
Constructors

COPY CONSTRUCTOR ????


Constructors in Java

➢ Constructors are the methods that are executed as soon as memory is

allocated for a particular object –

➢ in other words when the object is created in Random-Access-Memory,

the constructor is executed.

➢ The constructor method has name as same as class name.

➢ The constructors may take argument or may not take any argument
Constructors in Java

➢ If no constructor is defined for a class then a default constructor

without any parameter is considered implicitly.

➢ But if there is any constructor defined, then only those that are

defined is considered to be valid constructors.


//No Return Type
Constructors in Java

/* Here, Box uses a constructor to initialize the dimensions of a box. */


class Box {
double width;
double height;
double depth;

// This is the constructor for Box.

Box() {
[Link]("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
Constructors in Java

// compute and return volume // get volume of second box


double volume() { vol = [Link]();
return width * height * depth; [Link]("Volume is " + vol);
} }
} }
class BoxDemo {
public static void main(String args[]) {

// declare, allocate, and initialize Box objects


Box mybox1 = new Box();
Box mybox2 = new Box();
OUTPUT :
double vol; Constructing Box
// get volume of first box Constructing Box
vol = [Link](); Volume is 1000.0
[Link]("Volume is " + vol); Volume is 1000.0
Parameterized Constructors

/*Box uses a parameterized constructor to initialize the dimensions of a box. */

class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
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.

➢ Method overloading is one of the ways that Java implements


polymorphism.
Overloading Methods
// Demonstrate method overloading.
class OverloadDemo {
void test() {
[Link]("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
[Link]("a: " + a);
}

// Overload test for two integer parameters.


void test(int a, int b) {
[Link]("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
[Link]("double a: " + a);
return a*a;
}
}
Overloading Methods
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;

// call all versions of test() OUTPUT :


[Link](); No parameters
a: 10
[Link](10); a and b: 10 20
[Link](10, 20); double a: 123.25
Result of [Link](123.25): 15190.5625
result = [Link](123.25);
[Link]("Result of [Link](123.25): " + result);
}
}
Overloading Constructors

/* Box defines 3 constructors to initialize the dimensions of a box various ways*/


class Box {
double width;
double height;
double depth;

// constructor used when all dimensions specified

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


width = w;
height = h;
depth = d;
}
Overloading Constructors

// constructor used when no dimensions specified


Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}

// constructor used when cube is created


Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
Overloading Constructors

class OverloadCons {
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 = [Link]();
[Link]("Volume of mybox1 is " + vol);
// get volume of second box
vol = [Link]();
[Link]("Volume of mybox2 is " + vol);

// get volume of cube


vol = [Link](); OUTPUT :
[Link]("Volume of mycube is " + vol); Volume of mybox1 is 3000.0
} Volume of mybox2 is -1.0
} Volume of mycube is 343.0
Using Objects as Parameters

➢ One of the most common uses of object parameters involves

constructors.

➢ Frequently you will want to construct a new object so that it is

initially the same as some existing object.

➢ To do this, you must define a constructor that takes an object

of its class as a parameter.


Using Objects as Parameters

/*Here, Box allows one object to initialize another.*/


class Box {
double width;
double height; class OverloadCons2 {
double depth; public static void main(String args[]) {
Box() { Box mybox1=new Box();
width = -1; // use -1 to indicate Box myclone = new Box(mybox1);
height = -1; // an uninitialized
depth = -1; // box // get volume of clone
} vol = [Link]();
[Link]("Volume of clone is " +
// construct clone of an object vol);
Box(Box ob) { // pass object to constructor }
width = [Link];
height = [Link];
depth = [Link];
}
// compute and return volume
double volume() {
return width * height * depth;
}
Constructors and Methods
Understanding static

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

➢ Instance variables declared as static are, essentially, global variables.


Understanding static

➢ When objects of its class are declared, no copy of a static variable is

made. Instead, all instances of the class share the same static
variable.
➢ Methods declared as static have several restrictions:

■ They can only call other static methods.

■ They must only access static data.

■ They cannot refer to this or super in any way. (The keyword


super relates to inheritance)
Understanding static

// Demonstrate static variables, methods, and blocks.

class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
[Link]("x = " + x);
[Link]("a = " + a);
[Link]("b = " + b);
}
static { output of the program:
[Link]("Static block initialized."); Static block initialized.
b = a * 4; x = 42
} a=3
public static void main(String args[]) { b = 12
meth(42);
}
}
Introducing final

➢ A variable can be declared as final.

➢ Doing so prevents its contents from being modified.

➢ This means that you must initialize a final variable when it is declared.
(In this usage, final is similar to const in C/C++/C#.) For 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 = 5;
Nested and Inner Classes

➢ It is possible to define a class within another class; such

classes are known as nested classes

➢ A nested class has access to the members, including private

members, of the class in which it is nested.


Nested and Inner Classes

// Demonstrate an inner class.


class Outer {
int outer_x = 100; // Instance variable of the outer class

void test() {
Inner inner = new Inner(); // Create an object of inner class
[Link](); // Call method of inner class
}
[Link]();
}
// this is an inner class
class Inner {
void display() {
[Link]("display: outer_x = " + outer_x);
}
Output :
}
display: outer_x = 100
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer(); // Create instance of outer class
[Link](); // Call test() method which uses inner class
}
GARBAGE COLLECTION
Garbage Collection

➢ In some languages, such as C++, dynamically allocated objects must be


manually released by use of a delete operator.

➢ Java takes a different approach; it handles deallocation for you


automatically.

➢ The technique that accomplishes this is called garbage collection.

➢ It works like this: when no references to an object exist, that object is


assumed to be no longer needed, and the memory occupied by the
object can be reclaimed.
Garbage Collection

➢ There is no explicit need to destroy objects as in C++.

➢ Garbage collection only occurs sporadically (if at all) during the

execution of your program.


GARBAGE COLLECTION

➢Finalize() is the method of Object class.


➢This method is called just before an object is garbage collected.
➢finalize() method overrides to dispose system resources, perform
clean-up activities and minimize memory leaks.

SYNTAX :

protected void finalize() throws Throwable


The finalize( ) Method
➢ Sometimes an object will need to perform some action when it is

destroyed.

➢ To add a finalizer to a class, you simply define the finalize( ) method.

➢ The garbage collector runs periodically, checking for objects that are no

longer referenced by any running state or indirectly through other


referenced objects. Right before an asset is freed, the Java run time
calls the finalize( ) method on the object.
The finalize( ) Method

➢ The Java run time calls that method whenever it is about to recycle an

object of that class.

➢ To handle such situations, called finalization. By using finalization, you can

define specific actions that will occur when an object is just about to be
reclaimed by the garbage collector.

➢ Inside the finalize( ) method you will specify those actions that must be

performed before an object is destroyed.


The finalize( ) Method
➢ The finalize( ) method has this general form:

protected void finalize( )


{
// finalization code here
}
➢ Here, the keyword protected is a specifier that prevents access to

finalize( ) by code defined outside its class.


➢ It is important to understand that finalize( ) is only called just prior to

garbage collection
class FinalizeDemo {
protected void finalize() {
[Link]("finalize method called");
}
public static void main(String args[]) {
FinalizeDemo f1 = new FinalizeDemo();
FinalizeDemo f2 = new FinalizeDemo();
f1 = null; // f1 object is now eligible for GC
f2 = null; // f2 object is now eligible for GC

[Link](); // Request JVM to perform garbage collection

[Link]("End of main"); }
}
The this Keyword

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

➢ That is, this is always a reference to the object on which the

method was invoked.

➢ You can use this anywhere a reference to an object of the

current class’ type is permitted.


The this Keyword

➢ To better understand what this refers to, consider the

following version of Box( ):

// A redundant use of this.


Box(double w, double h, double d) {
[Link] = w;
[Link] = h;
[Link] = d;
}
VISIBILITY
ACCESS CONTROL
MODIFIERS
⚫Visibility modifiers are used to restrict the access to certain variables
and methods from outside the class.
⚫Also known as ACCESS MODIFIERS.

Visibility
Labels
DEFAULT

PUBLIC PROTECTED
PRIVATE
Introducing Access Control
➢ Through encapsulation, you can control what parts of a program can

access the members of a class. By controlling access, you can prevent


misuse.
➢ Java’s access specifiers are public, private, and protected.

➢ Java also defines a default access level. protected applies only when

inheritance is involved.
➢ When a member of a class is modified by the public specifies, then that

member can be accessed by any other code.


Introducing Access Control

➢ When a member of a class is specified as private, then that member

can only be accessed by other members of its class.


Here is an example:

public int i;
private double j;

private int myMethod(int a, char b) { // ...


ACCESS MODIFIERS (cont..)
Command-Line Arguments
➢ Sometimes you will want to pass information into a program when you
run it. This is accomplished by passing command-line arguments to
main( ).

➢ A command-line argument is the information that directly follows the


program’s name on the command line when it is executed.

➢ To access the command-line arguments inside a Java program is quite


easy—they are stored as strings in the String array passed to main( ).
For example, the following program displays all of the command-line
arguments that it is called with:
COMMAND LINE ARGUMENTS
Using Command-Line Arguments

class CommandLine {
public static void main(String args[]) {
for(int i=0; i<[Link]; i++)
[Link]("args[" + i + "]: " +args[i]);
}
}
output:
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
executing this program, as shown here: args[5]: -1
java CommandLine this is a test 100 -1
VARIABLE LENGTH ARGUMENTS

➢ Variable-length argument lists are a new feature in J2SE 5.0.

➢ Programmers can create methods that receive an unspecified number

of arguments.

➢ An argument type followed by an ellipsis (...) in a method's parameter

list indicates that the method receives a variable number of arguments


of that particular type.
Variable-Length Argument Lists

➢ This use of the ellipsis can occur only once in a parameter list, and the

ellipsis, together with its type, must be placed at the end of the
parameter list.

➢ Java treats the variable-length argument list as an array whose

elements are all of the same type.


Variable-Length Argument Lists
// Demonstrate variable-length arguments. public static void main(String args[])
class VarArgs { {
static void vaTest(int ... v) {
vaTest(10); // 1 arg
[Link]("Number of args: " +
vaTest(1, 2, 3); // 3 args
[Link] + " Contents: ");
vaTest(); // no args
for(int x : v)
{ }
[Link](x + " "); }
}
[Link]();
}
Variable-Length Argument Lists
public class VarargsTest
{
// calculate average
public static double average( double... numbers )
{
double total = 0.0; // initialize total
for ( double d : numbers )
total += d;
return total / [Link];
} //end of average
Variable-Length
Output :
Argument Lists d1 = 10.0
d2 = 20.0
public static void main( String args[] ) d3 = 30.0
d4 = 40.0
{
double d1 = 10.0; Average of d1 and d2 is 15.0
double d2 = 20.0; Average of d1, d2 and d3 is 20.0
double d3 = 30.0; Average of d1, d2, d3 and d4 is 25.0
double d4 = 40.0;
[Link]( "d1 = %.1f\nd2 = %.1f\nd3 = %.1f\nd4 = %.1f\n\n", d1, d2, d3, d4 );
[Link]( "Average of d1 and d2 is %.1f\n", average( d1, d2 ) );
[Link]( "Average of d1, d2 and d3 is %.1f\n", average( d1, d2, d3 ) );
[Link]( "Average of d1, d2, d3 and d4 is %.1f\n", average( d1, d2, d3, d4 ) );
} // end main
} // end class VarargsT

You might also like