Oops Through Java Btech 3rd Year Notes
Oops Through Java Btech 3rd Year Notes
Course Objectives:
2. Introduces The Principles Of Inheritance And Polymorphism; And Demonstrates How They
5. Introduces The Design Of Graphical User Interface Using Applets And Swings.
Course Outcomes:
UNIT - I:
Object Oriented Thinking and Java Basics: Need for OOP Paradigm, Summary of OOP Concepts,
Coping with Complexity, Abstraction Mechanisms, A Way of Viewing World – Agents, Responsibility,
Messages, Methods, History of Java, Java Buzzwords, Data Types, Variables, Scope and Life Time of
Variables, Arrays, Operators, Expressions, Control Statements, Type Conversion and Casting, Simple
Java Program, Concepts of Classes, Objects, Constructors, Methods, Access Control, This Keyword,
Garbage Collection, Overloading Methods and Constructors, Method Binding, Inheritance, Overriding
and Exceptions, Parameter Passing, Recursion, Nested and Inner Classes, Exploring String Class.
UNIT - II:
Inheritance, Packages and Interfaces: Hierarchical Abstractions, Base Class Object, Subclass,
Limitation, Combination, Benefits of Inheritance, Costs of Inheritance. Member Access Rules, Super
Uses, Using Final with Inheritance, Polymorphism- Method Overriding, Abstract Classes, The Object
Class.
Differences between Classes and Interfaces, Defining an Interface, Implementing Interface, Applying
Interfaces, Variables in Interface and Extending Interfaces, Exploring Java.IO.
UNIT - III:
Handling, Termination or Resumptive Models, Exception Hierarchy, Usage of Try, Catch, Throw,
Throws and Finally, Built in Exceptions, Creating Own Exception Sub Classes.
String Handling, Exploring Java.Util, Differences between Multi-Threading and Multitasking, Thread Life
UNIT - IV:
Event Handling: Events, Event Sources, Event Classes, Event Listeners, Delegation Event Model,
The AWT Class Hierarchy, User Interface Components- Labels, Button, Canvas, Scrollbars, Text
Components, Check Box, Check Box Groups, Choices, Lists Panels – Scrollpane, Dialogs, Menubar,
Graphics, Layout Manager – Layout Manager Types – Border, Grid, Flow, Card and Grid Bag.
UNIT - V:
Applets: Concepts f Applets, Differences between Applets and Applications, Life Cycle of an Applet,
Swing- Japplet, Jframe and Jcomponent, Icons and Labels, Text Fields, Buttons – The Jbutton Class,
Check Boxes, Radio Buttons, Combo Boxes, Tabbed Panes, Scroll Panes, Trees, and Tables.
TEXT BOOKS:
REFERENCE BOOKS:
1. An Introduction to Programming and OO Design using Java, J. Nino and F.A. Hosch, John Wiley &
Sons.
5. Core Java 2, Vol 1, Fundamentals, Cay. S. Horstmann and Gary Cornell, Eighth Edition, Pearson
Education.
6. Core Java 2, Vol 2, Advanced Features, Cay. S. Horstmann and Gary Cornell, eighth Edition, Pearson
Education
The History and Evolution of Java
To fully understand Java, one must understand the reasons behind its creation, the forces that shaped it,
and the legacy that it inherits. the creation of Java was deeply rooted in the process of refinement and
adaptation that has been occurring in computer programming languages for the past several decades.
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun
Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was
initially called “Oak,” but was renamed “Java” in 1995.
The Internet helped catapult Java to the forefront of programming, and Java, in turn, had a profound
effect on the Internet. In addition to simplifying web programming in general, Java innovated a new type
of networked program called the applet that changed the way the online world thought about content.
The key that allows Java to solve both the security and the portability problems just described is that the
output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly optimized set
of instructions designed to be executed by the Java run-time system, which is called the Java Virtual
Machine (JVM). In essence, the original JVM was designed as an interpreter for bytecode.
Translating a Java program into bytecode makes it much easier to run a program ina wide variety of
environments because only the JVM needs to be implemented for each platform. Once the run-time
package exists for a given system, any Java program can run on it. Remember, although the details of the
JVM will differ from platform to platform, all understand the same Java bytecode. If a Java program were
compiled to native code, then different versions of the same program would have to exist for each type of
CPU connected to the Internet. This is, of course, not a feasible solution. Thus, the execution of bytecode
by the JVM is the easiest way to create truly portable programs.
OBJECT-ORIENTED PROGRAMMING
Object-Oriented Programming (OOP) is a programming language model organized around objects
rather than actions and data. An object-oriented program can be characterized as data controlling
access to code. Concepts of OOPS
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
The popular object-oriented programming languages are Smalltalk, C++, Java, PHP, C#, Python, etc.
OBJECT
Object means a real word entity such as pen, chair, table etc. Any entity that has state and
behavior is
known as an object. Object can be defined as an instance of a class. An object contains an address
and takes up some space in memory. Objects can communicate without knowing details of each
other's data or code, the only necessary thing is that the type of message accepted and type of
response returned by the objects.
An object has three characteristics:
state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, it is used internally by the JVM to identify each object uniquely.
CLASS
Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint
from which you can create an individual object. A class consists of Data members and
methods.The primary purpose of a class is to hold data/information. The member functions
determine the behavior of the class, i.e. provide a definition for supporting various operations on
data held in the form of an object.Class doesn’t store any space.
INHERITANCE
Inheritance can be defined as the procedure or mechanism of acquiring all the properties and
behavior of one class to another, i.e., acquiring the properties and behavior of child class from the
parent class. When one object acquires all the properties and behaviours of another object, it is
known
as inheritance. It provides code reusability and establishes relationships between different classes.
A class which inherits the properties is known as Child Class(sub-class or derived class) whereas
a class whose properties are inherited is known as Parent class(super-class or base class).
Types of inheritance in java:
single, multilevel and hierarchical inheritance. Multiple and hybrid inheritance is supported
through
interface only.
POLYMORPHISM
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
ABSTRACTION
Abstraction is a process of hiding the implementation details and showing only functionality to
the
user. For example: phone call, we don't know the internal processing.In java, we use abstract class
and
interface to achieve abstraction.
ENCAPSULATION
Encapsulation in java is a process of wrapping code and data together into a single unit, for
example capsule i.e. mixed of several medicines. The java programming language uses the class concept
to implement encapsulation.
Java Buzz Words
java is the most popular object-oriented programming language. Java has many advanced features, a list of key features is known as
Java Buzz Words. The java team has listed the following terms as java buzz words.
● Simple
● Secure
● Portable
● Object-oriented
● Robust
● Multi-threaded
● Interpreted
● High performance
● Distributed
● Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code. Most of the syntaxes in java follow basic
programming language C and object-oriented programming concepts are similar to C++. In a java programming language, many
complicated features like pointers, operator overloading, structures, unions, etc. have been removed. One of the most useful features
is the garbage collector it makes java more simple.
Secure
Java is said to be more secure programming language because it does not have pointers concept, java provides a feature "applet"
which can be embedded into a web application. The applet in java does not allow access to other parts of the computer, which keeps
away from harmful programs like viruses and unauthorized access.
Portable
Portability is one of the core features of java which enables the java programs to run on any computer or operating system. For
example, an applet developed using java runs on a wide variety of CPUs, operating systems, and browsers connected to the Internet.
Object-oriented
Java is said to be a pure object-oriented programming language. In java, everything is an object. It supports all the features of the
object-oriented programming paradigm. The primitive data types java also implemented as objects using wrapper classes, but still, it
allows primitive data types to archive high-performance.
Robust
Java is more robust because the java code can be executed on a variety of environments, java has a strong memory management
mechanism (garbage collector), java is a strictly typed language, it has a strong set of exception handling mechanism, and many
more.
Multi-threaded
Java supports multi-threading programming, which allows us to write programs that do multiple operations simultaneously.
Interpreted
Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. The
byte code is interpreted to any machine code so that it runs on the native machine.
High performance
Java provides high performance with the help of features like JVM, interpretation, and its simplicity.
Distributed
Java programming language supports TCP/IP protocols which enable the java to support the distributed environment of the Internet.
Java also supports Remote Method Invocation (RMI), this feature enables a program to invoke methods across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running system and it has a dynamic
memory allocation and deallocation (objects and garbage collector).
of the Java language. These keywords cannot be used as identifiers. Thus, they cannot be used as names
for a variable, class, or method
1. Integers :This group includes byte, short, int, and long, which are for whole-valued signed
numbers.
2. Floating-point numbers : This group includes float and double, which represent numbers with
fractional precision.
3. Characters :This group includes char, which represents symbols in a character set, like letters and
numbers.
4. Boolean : This group includes boolean, which is a special type for representing true/false values.
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative
values.
byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127. Variables
of type byte are especially useful when you’re working with a stream of data from a network or file. They
are also useful when you’re working with raw binary data that may not be directly compatible with Java’s
other built-in types.
Byte variables are declared by use of the byte keyword. For example, the following declares two byte
variables called b and c:
Example : byte b, c;
short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least used Java type.
Here are some examples of short variable declarations:
int
The most commonly used integer type is int. It is a signed 32-bit type that has a range from
–2,147,483,648 to 2,147,483,647
long
long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold
the desired value. The range of a long is quite large. This makes it useful when big, whole numbers are
needed.
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that require
fractional precision. For example, calculations such as square root, or transcendentals such as sine and
cosine, result in a value whose precision requires a floating point type.
There are two kinds of floating-point types, float and double, which represent single- and double-
precision numbers, respectively. Their width and ranges are shown here:
Characters
In Java, the data type used to store characters is char. In Java char is a 16-bit type. The range of a char is 0
to 65,536.
Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of two possible values,
true or false. This is the type returned by all relational operators, as in the case of a < b. boolean is also
the type required by the conditional expressions that govern the control statements such as if and for.
Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an
identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their
visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable declaration is
shown here:
Here, type is one of Java’s atomic types, or the name of a class or interface.
All of the variables used have been declared at the start of the main( ) method. However, Java allows
variables to be declared within any block. A block defines a scope. Thus, each time you start a new block,
you are creating a new scope. A scope determines what objects are visible to other parts of your
program. It also determines the lifetime of those objects.
As a general rule, variables declared inside a scope are not visible (that is, accessible) to code that is
defined outside that scope. Thus, when you declare a variable within a scope, you are localizing that
variable and protecting it from unauthorized access and/or modification.
Scopes can be nested. For example, each time you create a block of code, you are creating a new, nested
scope. When this occurs, the outer scope encloses the inner scope. This means that objects declared in
the outer scope will be visible to code within the inner scope. However, the reverse is not true. Objects
declared within the inner scope will not be visible outside it.
// Demonstrate block scope.
class scope
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
Arrays
An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can
be created and may have one or more dimensions. A specific element in an array is accessed by its index.
Arrays offer a convenient means of grouping related information.
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you first must
create an array variable of the desired type. The general form of a one-dimensional array declaration is
type var-name[ ];
Here, type declares the element type (also called the base type) of the array. The element type
determines the data type of each element that comprises the array. Thus, the element type for the array
determines what type of data the array will hold. For example, the following declares an array named
month_days with the type “array of int”:
int month_days[];
Although this declaration establishes the fact that month_days is an array variable, no array actually
exists. To link month_days with an actual, physical array of integers, you must allocate one using new and
assign it to month_days. new is a special operator that allocates memory.
Use “new” to allocate memory for arrays. The general form of new as it applies to one-dimensional
That is, to use new to allocate an array, you must specify the type and number of elements to allocate.
The elements in the array allocated by new will automatically be initialized to zero (for numeric types),
false (for boolean), or null (for reference types, which are described in a later chapter). This example
allocates a 12-element array of integers and links them to month_days:
After this statement executes, month_days will refer to an array of 12 integers. Further, all elements in
the array will be initialized to zero.
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. For example, the following declares a two
dimensional array variable called twoD:
This allocates a 4 by 5 array and assigns it to twoD. Internally, this matrix is implemented as an array of
arrays of int.
int i, j, k = 0;
twoD[i][j] = k;
k++;
System.out.println();
01234
56789
10 11 12 13 14
15 16 17 18 19
OPERATORS
An operator is a symbol used to perform arithmetic and logical operations. Java provides
a rich set of operators.
In java, operators are clasiffied into the following four types.
● Arithmetic Operqators
● Relational (or) Comparision Operators
● Logical Operators
● Assignment Operators
● Bitwise Operators
● Conditional Operators
Arithmetic Operators
In java, arithmetic operators are used to performing basic mathematical operations like
addition, subtraction, multiplication, division, modulus, increment, decrement, etc.,
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
Operator Meaning Example
++ Increment a++
-- Decrement a--
Example
< Returns TRUE if the first value is smaller than second 10 < 5 is FALSE
value otherwise returns FALSE
Operator Meaning Example
> Returns TRUE if the first value is larger than second 10 > 5 is TRUE
value otherwise returns FALSE
<= Returns TRUE if the first value is smaller than or equal 10 <= 5 is
to second value otherwise returns FALSE FALSE
>= Returns TRUE if the first value is larger than or equal 10 >= 5 is TRUE
to second value otherwise returns FALSE
Example
public class RelationalOperators {
Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into
one condition. The following table provides information about logical operators.
& Logical AND - Returns TRUE if all conditions are false & true =>
TRUE otherwise returns FALSE false
^ Logical XOR - Returns FALSE if all conditions are true ^ true =>
same otherwise returns TRUE false
&& short-circuit AND - Similar to Logical AND (&), but false & true =>
once a decision is finalized it does not evaluate false
remianing.
Example
public class LogicalOperators {
public static void main(String[] args) {
int x = 10, y = 20, z = 0;
boolean a = true;
a = x>y && (z=x+y)>15;
System.out.println("a = " + a + ", and z = " + z);
a = x>y & (z=x+y)>15;
System.out.println("a = " + a + ", and z = " + z);
}
}
Assignment Operators
The assignment operators are used to assign right-hand side value (Rvalue) to the left-
hand side variable (Lvalue). The assignment operator is used in different variants along
with arithmetic operators. The following table describes all the assignment operators in
the java programming language.
+= Add both left and right-hand side values and store the A += 10
result into left-hand side variable
|= Logical OR assignment -
Operator Meaning Example
Example
public class AssignmentOperators {
Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java programming
language. When we use the bitwise operators, the operations are performed based on
binary values. The following table describes all the bitwise operators in the java
programming language.
Let us consider two v
ariables A and B as A = 25 (11001) and B = 20 (10100).
Operato
r Meaning Example
& the result of Bitwise AND is 1 if all the bits are 1 A&B
otherwise it is 0 ⇒ 16 (10000)
^ the result of Bitwise XOR is 0 if all the bits are same A^B
otherwise it is 1 ⇒ 13 (01101)
<< the Bitwise left shift operator shifts all the bits to the A << 2
left by the specified number of positions ⇒ 100
(1100100)
>> the Bitwise right shift operator shifts all the bits to the A >> 2
right by the specified number of positions ⇒ 6 (00110)
Example
public class BitwiseOperators {
Conditional Operators
The conditional operator is also called a ternary operator because it requires three
operands. This operator is used for decision making. In this operator, first, we verify a
condition, then we perform one operation out of the two operations based on the
condition result. If the condition is TRUE the first option is performed, if the condition is
FALSE the second option is performed. The conditional operator is used with the
following syntax.
Syntax
Condition ? TRUE Part : FALSE Part;
Example
public class ConditionalOperator {
Control Statements
A programming language uses control statements to cause the flow of execution to
advance and branch based on changes to the state of a program. Java’s program control
statements can be put into the following categories: selection, iteration, and jump.
Selection statements allow your program to choose different paths of execution based
upon the outcome of an expression or the state of a variable. Iteration statements enable
program execution to repeat one or more statements (that is, iteration statements form
loops). Jump statements allow your program to execute in a nonlinear fashion.
Java’s Selection Statements
Java supports two selection statements: if and switch. These statements allow you to
control the flow of your program’s execution based upon conditions known only during
run time.
The if statement
is Java’s conditional branch statement. It can be used to route program execution
through two different paths. Here is the general form of the if statement:
if (condition) statement1;
else statement2;
Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within the same block as the
else and that is not already associated with an else. Here is an example:
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
As the comments indicate, the final else is not associated with if(j<20) because it is not in
the same block (even though it is the nearest if without an else). Rather, the final else is
associated with if(i==10). The inner else refers to if(k>100) because it is the closest if
within the same block.
The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the if-
elseif ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
else
statement;
The if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of
the ladder is bypassed. If none of the conditions is true, then the final else statement will
be executed. The final else acts as a default condition; that is, if all other conditional tests
fail, then the last else statement is performed. If there is no final else and all other
conditions are false, then no action will take place.
Here is a program that uses an if-else-if ladder to determine which season a particular
month is in.
while(condition) {
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as
long as the conditional expression is true. When condition becomes false, control passes
to the next line of code immediately following the loop. The curly braces are unnecessary
if only a single statement is being repeated.
Here is a while loop that counts down from 10, printing exactly ten lines of "tick":
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates
the conditional expression. If this expression is true, the loop will repeat. Otherwise, the
loop terminates. As with all of Java’s loops, condition must be a Boolean expression.
Here is a reworked version of the “tick” program that demonstrates the do-while loop. It
generates the same output as before.
For loop
Tthere are two forms of the for loop. The first is the traditional form Here is the general
form of the traditional for statement:
The for loop operates as follows. When the loop first starts, the initialization portion of the
loop is executed. Generally, this is an expression that sets the value of the loop control
variable, which acts as a counter that controls the loop. It is important to understand that
the initialization expression is executed only once. Next, condition is evaluated. This
must be a Boolean expression. It usually tests the loop control variable against a target
value. If this expression is true, then the body of the loop is executed. If it is false, the
loop terminates. Next, the iteration portion of the loop is executed. This is usually an
expression that increments or decrements the loop control variable. The loop then
iterates, first evaluating the conditional expression, then executing the body of the loop,
and then executing the iteration expression with each pass. This process repeats until
the controlling expression is false.
Here is a version of the “tick” program that uses a for loop:
The general form of the for-each version of the for is shown here:
for(type itr-var : collection) statement-block
Here, type specifies the type and itr-var specifies the name of an iteration variable that
will receive the elements from a collection, one at a time, from beginning to end. The
collection being cycled through is specified by collection. There are various types of
collections that can be used with the for,
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}
}
}
The output produced by this program is shown here:
..........
.........
........
.......
......
.....
....
...
..
.
Jump Statements
Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of your program.
Using break
In Java, the break statement has three uses. First, as you have seen, it terminates a
statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it
can be used as a “civilized” form of goto. The last two uses are explained here.
Using break to Exit a Loop
By using break, you can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop. When a break statement is
encountered inside a loop, the loop is terminated and program control resumes at the
next statement following the loop.
Here is a simple example:
As you can see, although the for loop is designed to run from 0 to 99, the break
statement causes it to terminate early, when i equals 10.
Using continue
Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for
this particular iteration
The continue statement performs such an action. In while and do-while loops, a continue
statement causes control to be transferred directly to the conditional expression that
controls the loop. In a for loop, control goes first to the iteration portion of the for
statement and then to the conditional expression. For all three loops, any intermediate
code is bypassed.
Here is an example program that uses continue to cause two numbers to be printed on
each line:
// Demonstrate continue.
class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}
This code uses the % operator to check if i is even. If it is, the loop continues without
printing a newline. Here is the output from this program:
01
23
45
67
89
return
The last control statement is return. The return statement is used to explicitly return from
a method. That is, it causes program control to transfer back to the caller of the method.
As such, it is categorized as a jump statement.
At any time in a method, the return statement can be used to cause execution to branch
back to the caller of the method. Thus, the return statement immediately terminates the
method in which it is executed.
class
ava is an object-oriented programming language, so everything in java program must be based
on the object concept. In a java programming language, the class concept defines the skeleton of
an object. The class defines the blueprint of an object.
Creating a Class
In java, we use the keyword class to create a class. A class in java contains
properties as variables and behaviors as methods.
Following is the syntax of class in the java.
Syntax
class <ClassName>{
data members declaration;
methods defination;
}
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
Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the
class is said to be instantiated. All the objects that are created using a single class have
the same properties and methods. But the value of properties is different for every object.
Following is the syntax of class in the java.
Syntax
<ClassName> <objectName> = new <ClassName>( );
Example:
/* A program that uses the Box class. Call this file BoxDemo.java */
class Box
double width;
double height;
double depth;
class BoxDemo
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
You should call the file that contains this program BoxDemo.java, because the main( ) method is in the
class called BoxDemo, not the class called Box.
To run this program, you must execute BoxDemo.class. When you do, you will see the following output:
Volume is 3000.0
Constructor
A constructor is a special method of a class that has the same name as the class name.
The constructor gets executes automatically on object creation. It does not require the
explicit method call. A constructor may have parameters and access specifiers too. In
java, if you do not provide any constructor the compiler automatically creates a default
constructor.
Parameterized Constructor
The parameterized constructor is used to provide different values to distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can have
any number of parameters in the constructor.
The most common use of the this keyword is to eliminate the confusion between class attributes
and parameters with the same name
class overload
int a,b,c,sum;
this.a=a;
this.b=b;
sum=a+b;
this.a=a;
this.b=b;
this.c=c;
sum=a+b+c;
over.add(12,13);
over.add(12,34,56);
OUTPUT:
Addition of 2 nos is25
Addition of 3 nos is102
Garbage Collection
In java deallocation is done automatically. The technique that accomplishes this is called garbage
collection. 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. There is no explicit need to destroy object.
Overloading Methods
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 process is referred to as method overloading. Method overloading is one of the ways that Java
supports polymorphism.
When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to
determine which version of the overloaded method to actually call. Thus, overloaded methods must
differ in the type and/or number of their parameters. While overloaded methods may have different
return types, the return type alone is insufficient to distinguish two versions of a method. When Java
encounters a call to an overloaded method, it simply executes the version of the method whose
parameters match the arguments used in the call.
class OverloadDemo {
void test() {
System.out.println("No parameters");
void test(int a) {
double test(double a) {
return a*a;
}
class Overload {
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
No parameters
a: 10
a and b: 10 20
double a: 123.25
As you can see, test( ) is overloaded four times. The first version takes no parameters, the second takes
one integer parameter, the third takes two integer parameters, and the fourth takes one double
parameter. The fact that the fourth version of test( ) also returns a value is of no consequence relative to
overloading, since return types do not play a role in overload resolution.
Overloading Constructors
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.
Student(){
System.out.println("this a default constructor");
}
Output:
Student Id : 0
Student Name : null
Student Id : 10
Student Name : David
In the above example, the Student class constructor is overloaded with two different constructors,
I.e., default and parameterized.
Inheritance
It is a mechanism in which one object acquires all the properties and behaviors of a parent
object.
The extends keyword indicates that you are making a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
A class which is inherited is called a parent or superclass, and the new class is called child or
subclass.
class Employee{
float salary=40000;
int bonus=10000;
OUTPUT:
Programmer salary is:40000.0
Bonus of programmer is:10000
Single Inheritance
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
class TestInheritance{
d.bark();
d.eat();
}}
Output:
barking...
eating...
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
void bark(){System.out.println("barking...");}
void weep(){System.out.println("weeping...");}
class TestInheritance2{
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...