0% found this document useful (0 votes)
12 views77 pages

JAVA U2

The document provides an overview of Java programming concepts, focusing on classes and objects as fundamental components of object-oriented programming. It explains the structure of a class, including instance variables and methods, and discusses the process of declaring and instantiating objects. Additionally, it covers access modifiers, method declarations, and the significance of parameters in methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views77 pages

JAVA U2

The document provides an overview of Java programming concepts, focusing on classes and objects as fundamental components of object-oriented programming. It explains the structure of a class, including instance variables and methods, and discusses the process of declaring and instantiating objects. Additionally, it covers access modifiers, method declarations, and the significance of parameters in methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 77

JAVA PROGRAMMING

UNIT II

Concepts of classes, objects:

The class is at the core of Java. It is the logical construct upon which the entire Java language
is built because it defines the shape and nature of an object.

As such, the class forms the basis for object-oriented programming in Java. Any concept you wish
to implement in a Java program must be encapsulated within a class. Because the class is so
fundamental to Java.

Class Fundamentals:

The classes created in the preceding chapters primarily exist simply to encapsulate the
main( )method, which has been used to demonstrate the basics of the Java syntax.

Perhaps the most important thing to understand about a class is that it defines a new data
type, defined, this new type can be used to create objects of that type.

Thus, a class is a template for an object, and an object is an instance of a class.

Because an object is an instance of a class, you will often see the two words object and instance
used interchangeably.

The General Form of a Class:


JAVA PROGRAMMING

When you define a class, you declare its exact form and nature. You do this by specifying the
data that it contains and the code that operates on that data. While very simple classes may
contain only code or only data, most real-world classes contain both. As you will see, a class’
code defines the interface to its data.

A class is declared by use of the class keyword. The classes that have been used up to this
point are actually very limited examples of its complete form. Classes can (and usually do) get
much more complex. Asimplified general form of a class definition is shown here:

class classname {

type instance-variable1;

type instance-variable2;

// ...

type instance-variableN;

type methodname1(parameter-list) {

// body of method

}
JAVA PROGRAMMING

type methodname2(parameter-list) {

// body of method

// ...

type methodnameN(parameter-list) {

// body of method

The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class are
called members of the class. In most classes, the instance variables are acted upon and
accessed by the methods defined for that class. Thus, as a general rule, it is the methods that
determine how a class’ data can be used.
JAVA PROGRAMMING

Variables defined within a class are called instance variables because each instance of the class
(that is, each object of the class) contains its own copy of these variables. Thus, the data for one
object is separate and unique from the data for another.

All methods have the same general form as main( ), which we have been using thus far.
However, most methods will not be specified as static or public.

Notice that the general form of a class does not specify a main( )method. Java classes do not
need to have a main( ) method. You only specify one if that class is the starting point for your
program. Further, applets don’t require a main( ) method at all.

Declaring Member Variables

There are several kinds of variables:

 Member variables in a class—these are called fields.


 Variables in a method or block of code—these are called local variables.
 Variables in method declarations—these are called parameters.

The Bicycle class uses the following lines of code to define its fields:

public int cadence;


JAVA PROGRAMMING

public int gear;


public int speed;

Field declarations are composed of three components, in order:

1. Zero or more modifiers, such as public or private.


2. The field's type.
3. The field's name.

The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int).
The public keyword identifies these fields as public members, accessible by any object that can
access the class.

A Simple Class:

Let’s begin our study of the class with a simple example. Here is a class called Box that defines

three instance variables: width, height, and depth.

// This program declares two Box objects.

class Box {

double width;
JAVA PROGRAMMING

double height;

double depth;

class BoxDemo2 {

public static void main(String args[]) {

Box mybox1 = new Box();

Box mybox2 = new Box();

double vol;

// assign values to mybox1's instance variables

mybox1.width = 10;

mybox1.height = 20;

mybox1.depth = 15;

/* assign different values to mybox2's

instance variables */
JAVA PROGRAMMING

mybox2.width = 3;

mybox2.height = 6;

mybox2.depth = 9;

// compute volume of first box

vol = mybox1.width * mybox1.height * mybox1.depth;

System.out.println("Volume is " + vol);

// compute volume of second box

vol = mybox2.width * mybox2.height * mybox2.depth;

System.out.println("Volume is " + vol);

The output produced by this program is shown here:

Volume is 3000.0

Volume is 162.0
JAVA PROGRAMMING

 As you can see, mybox1’s data is completely separate from the data contained in mybox2.
 As stated, a class defines a new type of data. In this case, the new data type is called Box.

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

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

 After this statement executes, mybox will be an instance of Box. Thus, it will have
“physical” reality. For the moment, don’t worry about the details of this statement.
 To access these variables, you will use the dot (.) operator. The dot operator links the
name of the object with the name of an instance variable.

For example, to assign the width variable of mybox the value 100, you would use the following
statement:

mybox.width = 100;

This statement tells the compiler to assign the copy of width that is contained within the mybox
object the value of 100.

 In general, you use the dot operator to access both the instance variables and the
methods within an object.
 You should call the file that contains this program BoxDemo2.java, because the main()
method is in the class called BoxDemo2, not the class called Box.
JAVA PROGRAMMING

 When you compile this program, you will find that two .class files have been created, one
for Box and one for BoxDemo2.
 The Java compiler automatically puts each class into its own .class file. It is not necessary
for both the Box and the BoxDemo2 class to actually be in the same source file. You could
put each class in its own file, called Box.java and BoxDemo2.java, respectively.

To run this program, you must execute BoxDemo2.class. When you do, you will see the

following output:

Volume is 3000.0

Volume is 162.0

 As stated earlier, each object has its own copies of the instance variables.

This means that if you have two Box objects, each has its own copy of depth, width, and height.
It is important to understand that changes to the instance variables of one object have no effect
on the instance variables of another.

Declaring Objects

An object is an instance of a class. An object is known by a name and every object contains a
state. The state is determined by the values of attributes (variables). The state of an object can
JAVA PROGRAMMING

be changed by calling methods on it. The sequence of state changes represents the behavior of
the object.

An object is a software entity (unit) that combines a set of data with a set of operations to
manipulate that data.

As just explained, when you create a class, you are creating a new data type. You can use
this type to declare objects of that type.

However, obtaining objects of a class is a two-step process.

 First, you must declare a variable of the class type. This variable does not define an
object. Instead, it is simply a variable that can refer to an object.
 Second, you must acquire an actual, physical copy of the object and assign it to that
variable. You can do this using the new operator.

 Declaration: The code set in variable declarations that associate a variable name with an
object type.
 Instantiation: The new keyword is a Java operator that creates the object.
 Initialization: The new operator is followed by a call to a constructor, which initializes the
new object.
JAVA PROGRAMMING

The new operator dynamically allocates (that is, allocates at run time) memory for an object and
returns a reference to it. This reference is, more or less, the address in memory of the object
allocated by new. This reference is then stored in the variable. Thus, in Java, all class objects
must be dynamically allocated. Let’s look at the details of this procedure.

In the preceding sample programs, a line similar to the following is used to declare an object of
type Box:

Box mybox = new Box();

This statement combines the two steps just described. It can be rewritten like this to show each
step more clearly:

mybox = new Box(); // allocate a Box object

The first line declares mybox as a reference to an object of type Box. After this line executes,
mybox contains the value null, which indicates that it does not yet point to an actual object.

Any attempt to use mybox at this point will result in a compile-time error. The next line allocates
an actual object and assigns a reference to it to mybox. After the second line executes, you can
use mybox as if it were a Box object. But in reality, mybox simply holds the memory address of
the actual Box object. The effect of these two lines of code is depicted in Figure.
JAVA PROGRAMMING

Assigning Object Reference Variables:

Object reference variables act differently than you might expect when an assignment takes
place. For example, what do you think the following fragment does?

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
JAVA PROGRAMMING

object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original
object. 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.

This situation is depicted here:

Although b1 and b2 both refer to the same object, they are not linked in any other way.

For example, a subsequent assignment to b1 will simply unhook b1 from the original object
without affecting the object or affecting b2. For example:

Box b1 = new Box();

Box b2 = b1;

// ...

b1 = null;
JAVA PROGRAMMING

Here, b1 has been set to null, but b2 still points to the original object.

REMEMBER: When you assign one object reference variable to another object reference variable,
you are not creating a copy of the object, you are only making a copy of the reference.

Access Modifiers:

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

The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.

There are 4 types of java access modifiers:

1. private
2. default
3. protected
4. public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc.

1.private:
JAVA PROGRAMMING

Methods, Variables and Constructors that are declared private can only be accessed within the
declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.

Using the private modifier is the main way that an object encapsulates itself and hide data from
the outside world.

2.default:

If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within 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.

4.public:
JAVA PROGRAMMING

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

Understanding all java access modifiers

Let's understand the access modifiers by a simple table.

Access Modifier within class within package outside package by subclass only outside package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Methods :

Here is an example of a typical method declaration:

public double calculateAnswer(double width, int numberofitems,


double length, double height) {
JAVA PROGRAMMING

//do the calculation here


}

The only required elements of a method declaration are the method's return type, name, a pair
of parentheses, (), and a body between braces, {}.

More generally, method declarations have six components, in order:

1. Modifiers—such as public, private, and others you will learn about later.
2. The return type—the data type of the value returned by the method, or void if the method
does not return a value.
3. The method name—the rules for field names apply to method names as well, but the
convention is a little different.
4. The parameter list in parenthesis—a comma-delimited list of input parameters, preceded
by their data types, enclosed by parentheses, (). If there are no parameters, you must use
empty parentheses.
5. An exception list—to be discussed later.
6. The method body, enclosed between braces—the method's code, including the declaration
of local variables, goes here.

Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are
discussed in a later lesson.
JAVA PROGRAMMING

Definition: Two of the components of a method declaration comprise the method signature—
the method's name and the parameter types.

The signature of the method declared above is:

calculateAnswer(double, int, double, double)

Naming a Method

Although a method name can be any legal identifier, code conventions restrict method names.
By convention, method names should be a verb in lowercase or a multi-word name that begins
with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter
of each of the second and following words should be capitalized.

Here are some examples:

run
runFast
JAVA PROGRAMMING

getBackground
getFinalData
compareTo
setX
isEmpty

Typically, a method has a unique name within its class. However, a method might have the same
name as other methods due to method overloading.

Returning a Value from a Method

A method returns to the code that invoked it when it

 completes all the statements in the method,


 reaches a return statement, or
 throws an exception (covered later),

whichever occurs first.

You declare a method's return type in its method declaration. Within the body of the method,
you use the return statement to return the value.
JAVA PROGRAMMING

Any method declared void doesn't return a value. It does not need to contain a return statement,
but it may do so. In such a case, a return statement can be used to branch out of a control flow
block and exit the method and is simply used like this:

return;

If you try to return a value from a method that is declared void, you will get a compiler error.

Any method that is not declared void must contain a return statement with a corresponding
return value, like this:

returnValue;

The data type of the return value must match the method's declared return type; you can't
return an integer value from a method declared to return a boolean.

The getArea() method in the Rectangle Rectangle class that was discussed in the sections on
objects returns an integer:

// a method for computing the area of the rectangle


public int getArea() {
return width * height;
JAVA PROGRAMMING

This method returns the integer that the expression width*height evaluates to.

Parameters:

Parameters refers to the list of variables in a method declaration. Arguments are the actual
values that are passed in when the method is invoked. When you invoke a method, the
arguments used must match the declaration's parameters in type and order.

Parameter Types

You can use any data type for a parameter of a method or a constructor. This includes primitive
data types, such as doubles, floats, and integers.

Parameter Names

When you declare a parameter to a method or a constructor, you provide a name for that
parameter. This name is used within the method body to refer to the passed-in argument.

The name of a parameter must be unique in its scope. It cannot be the same as the name of
another parameter for the same method or constructor, and it cannot be the name of a local
variable within the method or constructor.
JAVA PROGRAMMING

parameter passing:

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. In this approach, a


reference to an argument (not the value of the argument) is passed to the parameter. Inside the
subroutine, this reference is used to access the actual argument specified in the call. This means
that changes made to the parameter will affect the argument used to call the subroutine.

As you will see, Java uses both approaches, depending upon what is passed.

In Java, when you pass a primitive 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.

For example, consider the following program:

// Primitive types are passed by value.

class Test {
JAVA PROGRAMMING

void meth(int i, int j) {

i *= 2;

j /= 2;

class CallByValue {

public static void main(String args[]) {

Test ob = new Test();

int a = 15, b = 20;

System.out.println("a and b before call: " +

a + " " + b);

ob.meth(a, b);

System.out.println("a and b after call: " +

a + " " + b);


JAVA PROGRAMMING

The output from this program is shown here:

a and b before call: 15 20

a and b after call: 15 20

As you can see, the operations that occur inside meth( ) have no effect on the values of a and b
used in the call; their values here did not change to 30 and 10.

When you pass an object to a method, the situation changes dramatically, because objects are
passed by what is effectively call-by-reference.

Keep in mind that when you create a variable of a class type, you are only creating a reference
to an object. Thus, when you pass this reference to a method, the parameter that receives it will
refer to the same object as that referred to by the argument. This effectively means that objects
are passed to methods by use of call-by-reference. Changes to the object inside the method do
affect the object used as an argument.

For example, consider the following program:

// Objects are passed by reference.


JAVA PROGRAMMING

class Test {

int a, b;

Test(int i, int j) {

a = i;

b = j;

// pass an object

void meth(Test o) {

o.a *= 2;

o.b /= 2;

class CallByRef {

public static void main(String args[]) {


JAVA PROGRAMMING

Test ob = new Test(15, 20);

System.out.println("ob.a and ob.b before call: " +

ob.a + " " + ob.b);

ob.meth(ob);

System.out.println("ob.a and ob.b after call: " +

ob.a + " " + ob.b);

This program generates the following output:

ob.a and ob.b before call: 15 20

ob.a and ob.b after call: 30 10

As you can see, in this case, the actions inside meth( ) have affected the object used as an
argument.
JAVA PROGRAMMING

As a point of interest, 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.

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

Overloading Methods

The Java programming language supports overloading methods, and Java can distinguish
between methods with different method signatures. This means that methods within a class can
have the same name if they have different parameter lists (there are some qualifications to this
that will be discussed in the lesson titled "Interfaces and Inheritance").

Suppose that you have a class that can use calligraphy to draw various types of data (strings,
integers, and so on) and that contains a method for drawing each data type. It is cumbersome to
use a new name for each method—for example, drawString, drawInteger, drawFloat, and so on.
In the Java programming language, you can use the same name for all the drawing methods but
pass a different argument list to each method. Thus, the data drawing class might declare four
methods named draw, each of which has a different parameter list.

public class DataArtist {


JAVA PROGRAMMING

...
public void draw(String s) {
...
}
public void draw(int i) {
...
}
public void draw(double f) {
...
}
public void draw(int i, double f) {
...
}
}

Overloaded methods are differentiated by the number and the type of the arguments passed
into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique
methods because they require different argument types.

You cannot declare more than one method with the same name and the same number and type
of arguments, because the compiler cannot tell them apart.
JAVA PROGRAMMING

The compiler does not consider return type when differentiating methods, so you cannot declare
two methods with the same signature even if they have a different return type.

Note: Overloaded methods should be used sparingly, as they can make code much less
readable.

Constructors:

It can be tedious to initialize all of the variables in a class each time an instance is created.
Because the requirement for initialization is so common, Java allows objects to initialize
themselves when they are created. This automatic initialization is performed through the use of
a constructor.

A constructor initializes an object immediately upon creation. It has the same name as the class
in which it resides and is syntactically similar to a method. Once defined, the constructor is
automatically called immediately after the object is created, before the new operator completes.
Constructors look a little strange because they have no return type, not even void. This is
because the implicit return type of a class’ constructor is the class type itself.

You can rework the Box example so that the dimensions of a box are automatically initialized
when an object is constructed. To do so, replace setDim( ) with a constructor.
JAVA PROGRAMMING

Let’s begin by defining a simple constructor that simply sets the dimensions of each box to the
same values. This version is shown here:

/* 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() {

System.out.println("Constructing Box");

width = 10;

height = 10;
JAVA PROGRAMMING

depth = 10;

// compute and return volume

double volume() {

return width * height * depth;

class BoxDemo6 {

public static void main(String args[]) {

// declare, allocate, and initialize Box objects

Box mybox1 = new Box();

Box mybox2 = new Box();


JAVA PROGRAMMING

double vol;

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume is " + vol);

// get volume of second box

vol = mybox2.volume();

System.out.println("Volume is " + vol);

When this program is run, it generates the following results:

Constructing Box

Constructing Box
JAVA PROGRAMMING

Volume is 1000.0

Volume is 1000.0

As you can see, both mybox1 and mybox2 were initialized by the Box( ) constructor when they
were created. Since the constructor gives all boxes the same dimensions, 10 by 10 by 10, both
mybox1 and mybox2 will have the same volume. The println( ) statement inside Box( ) is for the
sake of illustration only.

Parameterized Constructors

While the Box( ) constructor in the preceding example does initialize a Box object, it is not very
useful—all boxes have the same dimensions. What is needed is a way to construct Box objects of
various dimensions. The easy solution is to add parameters to the constructor.

As you can probably guess, this makes them much more useful. For example, the following
version of Box defines a parameterized constructor that sets the dimensions of a box as specified
by those parameters. Pay special attention to how Box objects are created.

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

class Box {
JAVA PROGRAMMING

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;


JAVA PROGRAMMING

class BoxDemo7 {

public static void main(String args[]) {

// declare, allocate, and initialize Box objects

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

Box mybox2 = new Box(3, 6, 9);

double vol;

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume is " + vol);

// get volume of second box


JAVA PROGRAMMING

vol = mybox2.volume();

System.out.println("Volume is " + vol);

The output from this program is shown here:

Volume is 3000.0

Volume is 162.0

As you can see, each object is initialized as specified in the parameters to its constructor.

For example, in the following line,

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

the values 10, 20, and 15 are passed to the Box( ) constructor when new creates the object.
Thus, mybox1’s copy of width, height, and depth will contain the values 10, 20, and 15,
respectively.
JAVA PROGRAMMING

Overloading Constructors:

Since Box( ) requires three arguments, it’s an error to call it without them.

This raises some important questions.

What if you simply wanted a box and did not care (or know) what its initial dimensions were? Or,
what if you want to be able to initialize a cube by specifying only one value that would be used
for all three dimensions?

As the Box class is currently written, these other options are not available to you.

Fortunately, the solution to these problems is quite easy: simply overload the Box constructor so
that it handles the situations just described. Here is a program that contains an improved version
of Box that does just that:

/* Here, Box defines three constructors to initialize

the dimensions of a box various ways.

*/

class Box {

double width;
JAVA PROGRAMMING

double height;

double depth;

// constructor used when all dimensions specified

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

width = w;

height = h;

depth = d;

// constructor used when no dimensions specified

Box() {

width = -1; // use -1 to indicate

height = -1; // an uninitialized

depth = -1; // box

}
JAVA PROGRAMMING

// constructor used when cube is created

Box(double len) {

width = height = depth = len;

// compute and return volume

double volume() {

return width * height * depth;

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


JAVA PROGRAMMING

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

The output produced by this program is shown here:


JAVA PROGRAMMING

Volume of mybox1 is 3000.0

Volume of mybox2 is -1.0

Volume of mycube is 343.0

As you can see, the proper overloaded constructor is called based upon the parameters specified
when new is executed.

Recursion:

Java supports recursion. Recursion is the process of defining something in terms of itself. As it
relates to Java programming, recursion is the attribute that allows a method to call itself.

A method that calls itself is said to be recursive.

The classic example of recursion is the computation of the factorial of a number. The factorial of
a number N is the product of all the whole numbers between 1 and N.

For example, 3 factorial is 1 × 2 × 3, or 6. Here is how a factorial can be computed by use of a


recursive method:

// A simple example of recursion.

class Factorial {
JAVA PROGRAMMING

// this is a recursive method

int fact(int n) {

int result;

if(n==1) return 1;

result = fact(n-1) * n;

return result;

class Recursion {

public static void main(String args[]) {

Factorial f = new Factorial();

System.out.println("Factorial of 3 is " + f.fact(3));

System.out.println("Factorial of 4 is " + f.fact(4));

System.out.println("Factorial of 5 is " + f.fact(5));


JAVA PROGRAMMING

The output from this program is shown here:

Factorial of 3 is 6

Factorial of 4 is 24

Factorial of 5 is 120

Garbage Collection:
In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically.

Advantage of Garbage Collection:


 It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
JAVA PROGRAMMING

 It is automatically done by the garbage collector so we don't need to make extra efforts.

How can an object be unreferenced?


There are many ways:

 By nulling the reference


 By assigning a reference to another
 By annonymous object etc.

1) By nulling a reference:

Employee e=new Employee();

e=null;

2) By assigning a reference to another:

Employee e1=new Employee();

Employee e2=new Employee();


JAVA PROGRAMMING

e1=e2;//now the first object referred by e1 is available for garbage collection

3) By annonymous object:

new Employee();

finalize() method:
The finalize() method is invoked each time before the object is garbage collected. This method can be
used to perform cleanup processing. This method is defined in System class as:

protected void finalize(){}

Understanding static:

The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
JAVA PROGRAMMING

3. block
4. nested class

Java static variable

If you declare any variable as static, it is known static variable.

 The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students etc.
 The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Java static method

If you apply static keyword with any method, it is known as static method.

 A static method belongs to the class rather than object of a class.


 A static method can be invoked without the need for creating an instance of a class.
 static method can access static data member and can change the value of it.
JAVA PROGRAMMING

why java main method is static?


Because object is not required to call static method if it were non-static method, jvm create object first
then call main() method that will lead the problem of extra memory allocation.

Example of static method, variable:

//Program of changing the common property of all objects(static field).

class Student9{

int rollno;

String name;

static String college = "ITS";

static void change(){


JAVA PROGRAMMING

college = "BBDIT";

Student9(int r, String n){

rollno = r;

name = n;

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


JAVA PROGRAMMING

Student9.change();

Student9 s1 = new Student9 (111,"Karan");

Student9 s2 = new Student9 (222,"Aryan");

Student9 s3 = new Student9 (333,"Sonoo");

s1.display();

s2.display();

s3.display();

}
JAVA PROGRAMMING

Test it Now
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Java static block

 Is used to initialize the static data member.


 It is executed before main method at the time of classloading.

Example of static block

class A2{

static{System.out.println("static block is invoked");}

public static void main(String args[]){

System.out.println("Hello main");

}
JAVA PROGRAMMING

Output:static block is invoked


Hello main

Nested Classes

The Java programming language allows you to define a class within another class. Such a class is
called a nested class and is illustrated here:

class OuterClass {
...
class NestedClass {
...
}
}
Nested classes are divided into two categories: static and non-static. Nested classes that
are declared static are called static nested classes. Non-static nested classes are called inner
classes.

class OuterClass {
JAVA PROGRAMMING

...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}

Static Nested Classes:

As with class methods and variables, a static nested class is associated with its outer class. And
like static class methods, a static nested class cannot refer directly to instance variables or
methods defined in its enclosing class: it can use them only through an object reference.

Non Static Nested Classes(Inner class):

Non static nested class is also known as inner class. It has access to all variables and methods of
outer class and may refer to them directly. But the reverse is not true, that is outer class cannot
directly access members of inner class. One more thing is an inner class must created and
instantiated within the scope of outer class only.
JAVA PROGRAMMING

Inheritance

Inheritance is the mechanism of deriving new class from old one, old class is knows as
superclass and new class is known as subclass. The subclass inherits all of its instances variables
and methods defined by the superclass and it also adds its own unique elements. Thus we can
say that subclass are specialized version of superclass.

Types of Inheritance:

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid inheritance
6. Multipath inheritance

1.Single inheritance:

Here One subclass is deriving from one super class.

A SUPER CLASS A

EXTENDS

SUB CLASS B
B
JAVA PROGRAMMING

2.Multilevel Inheritance:

In multilevel inheritance the class is derived from the derived class.

SUPER-CLASS
A
EXTENDS

SUB-CLASS
B
EXTENDS

C SUB-SUBCLASS

3.Hierarchical Inheritance:

Only one base class but many derived classes.

SUPERCLASS
Figure

EXTENDS

Rectangle Triangle SUBCLASS

4.Multiple Inheritance:
JAVA PROGRAMMING

Deriving one subclass from more than one super classes is called multiple inheritance.

INTERFACE1 INTERFACE2
A B
(Animal) (Bird)

IMPLEMENTS

SUBCLASS

5.Hybrid Inheritance:

It is a combination of multiple and hierarchical inheritance.

A
HIERARCHICAL INHERITANCE

B C

D MULTIPLE INHERITANCE

6.Multipath Inheritance:

B C
JAVA PROGRAMMING

Benefits of Inheritance:

The benefits of inheritance are as follows:

 Increased reliability
 Software reusability
 Code sharing
 To create software components
 Consistency of interface
 Polymorphism
 Information hiding
 Rapid prototyping

Increased Reliability: If a code is frequently executed then it will have very less amount of bugs,
compared to code that is not frequently executed.(error free code)

Software reusability: properties of a parent class can be inherited by a child class. But, it does
not require to rewrite the code of the inherited property in the child class. In OOPs, methods can
be written once but can be reused.

Code sharing: At one level of code sharing multiple projects or users can use a single class.
JAVA PROGRAMMING

Software components: Programmers can construct software components that are reusable using
inheritance.

Consistency of interfaces: when multiple classes inherit the behavior of a single super class all
those classes will now have the same behavior.

Polymorphism: Oops follows the bottom-up approach. And abstraction is high at top, these are
exhibit the different behaviors based on instances.

Information hiding: interfaces’s or abstracts classes’s methods definition is in super class,


methods implementation is in subclasses. Means we know what to do but not how to do.

Rapid prototyping: By using the same code for different purposes, we can reduce the lengthy
code of the program.

Cost of inheritance:

Following are the costs of inheritance:

 Program size: If the cost of memory decreases, then the program size does not matter.
Instead of limiting the program sizes, there is a need to produce code rapidly that has high
quality and is also error-free.
 Execution speed: The specialized code is much faster than the inherited methods that
manage the random subclasses.
 Program complexity: Complexity of a program may be increased if inheritance is overused.
 Message-passing: The cost of message passing is very less when execution speed is
considered.

Member access rules:

Java provides many levels of protection to allow fine-grained control over the visibility of
variables and methods within classes, subclasses, and packages.
JAVA PROGRAMMING

Classes and packages are both means of encapsulating and containing the name space and
scope of variables and methods. Packages act as containers for classes and other subordinate
packages.

Classes act as containers for data and code.

The class is Java’s smallest unit of abstraction. Because of the interplay between classes and
packages.

Java addresses four categories of visibility for class members:

• Subclasses in the same package

• Non-subclasses in the same package

• Subclasses in different packages

• Classes that are neither in the same package nor subclasses


JAVA PROGRAMMING

Table : class member access

We can protect the data from unauthorized access. To do this ,we are using access specifiers.

An access specifier is a keyword that is used to specify how to access a member of a class or the
class itself. There are four access specifiers in java:

private: private members of a class are not available outside the class.

public: public members of a class are available anywhere outside the class.

protected: If you want to allow an element to be seen outside your current package, but only to
classes that subclass your class directly, then declare that element protected.
JAVA PROGRAMMING

default: if no access specifier is used then default specifier is used by java compiler.
Default members are available outside the class. Specification, it is visible to subclasses as well
as to other classes in the same package. This is the default access.

Super Uses:

Whenever a subclass needs to refer to its immediate super class, it can do so by the use of the
keyword super.

Super has the two general forms.

1. super (args-list) : calls the Super class’s constructor.


2. Super . member: To access a member of the super class that has been hidden by a
member of a subclass. Member may be variable or method.

Use: Overriden methods allow Java to support Run-time polymorphism. This leads to Robustness
by Reusability.

The keyword ‘super’:

super can be used to refer super class variables as: super.variable

super can be used to refer super class methods as: super.method ()

super can be used to refer super class constructor as: super (values)

Example program for

super can be used to refer super class constructor as: super (values)
JAVA PROGRAMMING

class Figure

double dim1;

double dim2;

Figure(double a,double b)

dim1=a;

dim2=b;

double area()

System.out.println("Area for figure is undefined");

return 0;

}
JAVA PROGRAMMING

class Rectangle extends Figure

Rectangle(double a,double b)

{ calling super class constructor

super(a,b);

double area()

System.out.println("Inside area for rectangle");

return dim1*dim2;

class Triangle extends Figure

Triangle(double a,double b)
JAVA PROGRAMMING

super(a,b);

double area()

System.out.println("Inside area for triangle");

return dim1*dim2/2;

class FindAreas

public static void main(String args[])

Figure f=new Figure(10,10);

Rectangle r=new Rectangle(9,5);

Triangle t=new Triangle(10,8);


JAVA PROGRAMMING

Figure figref;

figref=r;

System.out.println("area is"+figref.area());

figref=t;

System.out.println("area is"+figref.area());

figref=f;

System.out.println("area is"+figref.area());

OUTPUT:

Inside area for rectangle

area is 45

Inside area for triangle

area is 40

Inside area for figure is undefined

area is 0
JAVA PROGRAMMING

2.Accessing the member of a super class:

The second form of super acts somewhat like this, except that it always refers to the superclass
of the subclass in which it is used. This usage has the following general form:

super.member;

Here, member can be either a method or an instance variable. This second form of super is most
applicable to situations in which member names of a subclass hide members by the same name
in the superclass. Consider this simple class hierarchy:

// Using super to overcome name hiding.

class A {

int i;

// Create a subclass by extending class A.

class B extends A {

int i; // this i hides the i in A

B(int a, int b) {

super.i = a; // i in A
JAVA PROGRAMMING

i = b; // i in B

void show() {

System.out.println("i in superclass: " + super.i);

System.out.println("i in subclass: " + i);

class UseSuper {

public static void main(String args[]) {

B subOb = new B(1, 2);

subOb.show();

This program displays the following:

i in superclass: 1

i in subclass: 2
JAVA PROGRAMMING

Although the instance variable i in B hides the i in A, super allows access to the i defined in the
superclass. As you will see, super can also be used to call methods that are hidden by a subclass.

Super uses: super class’s method access

import java.io.*;

class A

void display()

System.out.println("hi");

class B extends A

void display() calling super class method

super.display();
JAVA PROGRAMMING

System.out.println("hello");

static public void main(String args[])

B b=new B();

b.display();

Output: hi

Hello

Hierarchical Abstraction
JAVA PROGRAMMING

• An essential element of object-oriented programming is abstraction.


• Humans manage complexity through abstraction. For example, people do not think of a
car as a set of tens of thousands of individual parts. They think of it as a well-defined
object with its own unique behavior.
• This abstraction allows people to use a car without being overwhelmed by the complexity of
the parts that form the car. They can ignore the details of how the engine, transmission, and
braking systems work.
• Instead they are free to utilize the object as a whole.
JAVA PROGRAMMING

Class Hierarchy

• A child class of one parent can be the parent of another child, forming class
hierarchies

Animal

Reptile Bird Mammal

Snake Lizard Parrot Horse Bat

„ At the top of the hierarchy there’s a default class called Object


JAVA PROGRAMMING

Class Hierarchy

• Good class design puts all common features as high in the hierarchy as reasonable
• The class hierarchy determines how methods are executed
• inheritance is transitive
– An instance of class Parrot is also an instance of Bird, an instance of Animal, …, and an instance of
class Object
JAVA PROGRAMMING

Base Class Object

• In Java, all classes use inheritance.

• If no parent class is specified explicitly, the base class Object is implicitly inherited.

• All classes defined in Java, is a child of Object class, which provides minimal functionality guaranteed to
e common to all objects.
JAVA PROGRAMMING

Base Class Object


(cont)

Methods defined in Object class are;

1.equals(Object obj) Determine whether the argument object is the same as the
receiver.

2.getClass() Returns the class of the receiver, an object of type Class.

3.hashCode() Returns a hash value for this object. Should be overridden when the equals method is
changed.

4.toString() Converts object into a string value. This method is also often overridden.
JAVA PROGRAMMING

Base class

1) a class obtains variables and methods from another class


2) the former is called subclass, the latter super-class (Base class)
3) a sub-class provides a specialized behavior with respect to its super-class
4) inheritance facilitates code reuse and avoids duplication of data
JAVA PROGRAMMING

• One of the pillars of object-orientation.


• A new class is derived from an existing class:
1) existing class is called super-class
2) derived class is called sub-class
• A sub-class is a specialized version of its super-class:
1) has all non-private members of its
super-class
2) may provide its own implementation of super-class methods
• Objects of a sub-class are a special kind of objects of a super-class.
JAVA PROGRAMMING

extends

 Is a keyword used to inherit a class from another class


 Allows to extend from only one class

class One class Two extends One

{ {

int a=5; int b=10;

} }
JAVA PROGRAMMING

• One baseobj;// base class object.

• super class object baseobj can be used to refer its sub class objects.
• For example, Two subobj=new Two;
• Baseobj=subobj // now its pointing to sub class

You might also like