0% found this document useful (0 votes)
7 views26 pages

Java Classes and Objects Explained

Java
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)
7 views26 pages

Java Classes and Objects Explained

Java
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

1

UNIT II
Classes: Classes, Objects, Methods, Parameters, Constructors, Garbage Collection, Access
modifiers, Pass Objects and arguments, Method and Constructor Overloading,
Understanding static, Nested and inner classes.
Inheritance – Basics, Member Access, Usage of Super, Multi level hierarchy, Method
overriding, Abstract class, Final keyword.
Interfaces –Creating, Implementing, Using, Extending, and Nesting of interfaces.
Packages – Defining, Finding, Member Access, Importing.

CLASSES AND OBJECTS:


✓ A class is a template for an object, and an object is an instance of a class.
The General Form of a Class
✓ When a class is defined, its exact form and nature is declared by specifying the data that it contains and
the code that operates on that data.
✓ A class is declared by use of the class keyword.
class class-name{
// declare instance variables
type var1;
type var2;
//…….
type varN;
// declare methods
type method1( parameters){
//body of method
}
type method2( parameters){
//body of method
}
//…..
type methodN( parameters){
//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.
✓ Each instance of the class (that is, each object of the class) contains its own copy of these variables
Defining a class:
class Vehicle {
int passengers; // number of passengers
int fuelCap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
}
class declaration is only a type description: it does not create an actual object To
actually create a Vehicle object, use a statement like the following
Vehicle minivan = new Vehicle( ); // create a vehicle object called minivan
After this statement executes, minivan will be an instance of Vehicle. Thus, it will have “physical”
reality.
✓ Thus, every Vehicle object will contain its own copies of the instance variables passengers, fuelCap, mpg.
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.
[Link];
[Link]=16;

JAtfA PROGRAMMING
/* A program that uses the Vehicle class.
Call this file [Link]
*/
class Vehicle {
int passengers; // number of passengers
int fuelCap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
}

// This class declares an object of type Vehicle.


class VehicleDemo {
public static void main(String[ ] args) {
Vehicle minivan = new Vehicle();
int range;
// assign values to fields in minivan
[Link] = 7;
[Link] = 16;
[Link] = 21;
// compute the range assuming a full tank of gas
range = [Link] * [Link];
[Link]("Minivan can carry " + [Link] +
“with a range of " + range);
}
}
✓ When this program is compiled, two .class files have been created. The Java compiler automatically
puts each class into its own .class file.
✓ To run this program we must run [Link].

// This program creates two Vehicle objects.

class Vehicle {
int passengers; // number of passengers
int fuelCap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
}

// This class declares an object of type Vehicle.


class TwoVehicles {
public static void main(String[] args) {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
int range1, range2;

// assign values to fields in minivan


[Link] = 7;
[Link] = 16;
[Link] = 21;

// assign values to fields in sportscar


[Link] = 2;
[Link] = 14;
[Link] = 12;

// compute the ranges assuming a full tank of gas


range1 = [Link] * [Link];
range2 = [Link] * [Link];
[Link]("Minivan can carry " + [Link] + " with a range of " + range1);
[Link]("Sportscar can carry " + [Link] +" with a range of " + range2);
JAtfA PROGRAMMING
}
}

JAtfA PROGRAMMING
DECLARING OBJECTS
✓ 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. This can
be done by using the new operator.
✓ 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.

Vehicle minivan; // declare reference to object


NULL
minivan
minivan = new Vehicle( ); // allocate a Vehicle object

passengers
fuelcap
mpg
minivan
Vehicle object

REFERENCE VARIABLES AND ASSIGNMENTS


✓ Object reference variables act differently when an assignment takes place.
✓ Consider the following fragment:
Vehicle car1= new Vehicle( );
Vehicle car2= car1;

passengers
fuelcap
car1 mpg

car2
After this fragment executes, car1 and car2 will both refer to the same object. The assignment of car1
to car2 did not allocate any memory or copy any part of the original object. It simply makes car2 refer
to the same object as does car1. Thus, any changes made to the object through car2 will affect the
object to which car1 is referring, since they are the same object.
[Link]=26;
✓ When the following statements are executed display the same value 26
[Link]([Link]);
[Link]([Link]);

✓ Although car1 and car2 both refer to the same object, they are not linked in any other way. Vehicle
car1= new Vehicle( );
Vehicle car2= car1;
Vehicle car3= new Vehicle( );
car2=car3;

✓ After this statement executes car2 refers to the same object as car3. The object referred to by
car1 is exchanged.

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.

JAtfA PROGRAMMING
Methods
✓ A method contains the statements that define its actions. 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. This can be any valid type, including class
types that you create. If the method does not return a value, its return type must be void.
✓ 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. If the
method has no parameters, then the parameter list will be empty.

Adding a Method to the Vehicle Class


✓ Most of the time, methods are used to access the instance variables defined by the class. In fact, methods
define the interface to most classes. This allows the class implementer to hide the specific layout of internal
data structures behind cleaner method abstractions.

// Add range to Vehicle.


class Vehicle {
int passengers; // number of passengers
int fuelCap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
// Display the range.
void range( ) {
[Link]("Range is " + fuelCap * mpg);
}
}

class AddMeth {
public static void main(String[] args) {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
int range1, range2;

// assign values to fields in minivan


[Link] = 7;
[Link] = 16;
[Link] = 21;

// assign values to fields in sportscar


[Link] = 2;
[Link] = 14;
[Link] = 12;
[Link]("Minivan can carry " + [Link] + ". ");
[Link]( ); // display range of minivan
[Link]("Sportscar can carry " + [Link] + ". ");
[Link]( ); // display range of sportscar.
}
}

✓ When a method is called, program control is transferred to the method. When the method terminates,
control is transferred back to the caller, and execution resumes with the line of code following the call.
✓ When a method uses an instance variable that is defined by its class, it does so directly, without explicit
reference to an object and without use of the dot operator.

Returning from a method:


In general, two conditions can cause a method to return- first, when the method’s closing brace is
encountered. The second is when a return statement is executed. There are two forms of return – one
for use in void methods and one for returning values.

JAtfA PROGRAMMING
Returning a value:
✓ 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.
// Use a return value.
class Vehicle {
int passengers; // number of passengers
int fuelCap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
// Return the range.
int range( ) {
return mpg * fuelCap;
}
}
class RetMeth {
public static void main(String[ ] args) {
Vehicle minivan = new Vehicle( );
Vehicle sportscar = new Vehicle( );
int range1, range2;
// assign values to fields in minivan
[Link] = 7;
[Link] = 16;
[Link] = 21;
// assign values to fields in sportscar
[Link] = 2;
[Link] = 14;
[Link] = 12;
// get the ranges
range1 = [Link]();
range2 =
[Link]();
[Link]("Minivan can carry " + [Link] +“with range of " + range1 + " miles");
[Link]("Sportscar can carry " + [Link] + “with range of "+range2 + " miles");
}
}
Using parameters:
✓ It is possible to pass one or more values to a method when the method is called.
✓ Parameters allow a method to be generalized. That is, a parameterized method can operate on a variety
of data and/or be used in a number of slightly different situations.
✓ There are two important things to understand about returning values:
• The type of data returned by a method must be compatible with the return type specified by the method.
For example, if the return type of some method is boolean, you could not return an integer.
• The variable receiving the value returned by a method must also be compatible with the return type
specified for the method.
// A simple example that uses a parameter.
class ChkNum {
// Return true if x is even.
boolean isEven(int x) {
if((x% 2) == 0) return true;
else return false;
}
}
class ParmDemo {
public static void main(String[ ] args) {
ChkNum e = new ChkNum( );
if([Link](10)) [Link]("10 is
even."); if([Link](9)) [Link]("9 is
even."); if([Link](8)) [Link]("8 is
even.");
JAtfA PROGRAMMING
}
}

JAtfA PROGRAMMING
A method can have more than one parameter. Simply declare each parameter, separating one
from the next with a comma.
class Factor {
// Return true if a is a factor of b.
boolean isFactor(int a, int b) {
if( (b % a) == 0) return true;
else return false;
}
}
class IsFact {
public static void main(String[] args) {
Factor x = new Factor( );
if([Link](2, 20)) [Link]("2 is factor");
if([Link](3, 20)) [Link]("this won't be displayed");
}
}

Adding a parameterized method to Vehicle:


/*
Add a parameterized method that computes the fuel required for a given distance.
*/
class Vehicle {
int passengers; // number of passengers
int fuelCap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
// Return the range.
int range( ) {
return mpg * fuelCap;
}
// Compute fuel needed for a given distance.
double fuelNeeded(int miles) {
return (double) miles / mpg;
}
}
class CompFuel {
public static void main(String[ ] args) {
Vehicle minivan = new Vehicle( );
Vehicle sportscar = new Vehicle( );
double gallons;
int dist = 252;
// assign values to fields in minivan
[Link] = 7;
[Link] = 16;
[Link] = 21;
// assign values to fields in sportscar
[Link] = 2;
[Link] = 14;
[Link] = 12;
gallons = [Link](dist);
[Link]("To go " + dist + " miles minivan needs " + gallons + " gallons of fuel.");
gallons = [Link](dist);
[Link]("To go " + dist + " miles sportscar needs " + gallons + " gallons of fuel.");
}
}

JAtfA PROGRAMMING
CONSTRUCTORS:
✓ 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.
// A simple constructor.
class MyClass
{ int x;
MyClass( ) {
x = 10;
}
}
class ConsDemo {
public static void main(String[ ] args) {
MyClass t1 = new MyClass( );
MyClass t2 = new MyClass( );
[Link](t1.x + " " + t2.x);
}
}

Parameterized Constructors
✓ Parameters are added to a constructor in the same way that they are added to a method: just declare
them inside the parenthesis after the constructor’s name.
// A parameterized constructor.
class MyClass {
int x;
MyClass(int i) {
x = i;
}
}
class ParmConsDemo {
public static void main(String[ ] args) {
MyClass t1 = new MyClass(10);
MyClass t2 = new MyClass(88);
[Link](t1.x + " " + t2.x);
}
}

Adding a Constructor to a Vehicle calss


// Add a constructor.
class Vehicle {
int passengers; // number of passengers
int fuelCap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
// This is a constructor for Vehicle.
Vehicle(int p, int f, int m) {
passengers =
p; fuelCap = f;
mpg = m;
}
// Return the range.
int range( ) {
return mpg * fuelCap;
}
// Compute fuel needed for a given distance.
double fuelNeeded(int miles) {
return (double) miles / mpg;
}
JAtfA PROGRAMMING
}

JAtfA PROGRAMMING
class VehConsDemo {
public static void main(String[] args) {
// construct complete vehicles
Vehicle minivan = new Vehicle(7, 16, 21);
Vehicle sportscar = new Vehicle(2, 14,
12); double gallons;
int dist = 252;
gallons = [Link](dist);
[Link]("To go " + dist + " miles minivan needs " +
gallons + " gallons of fuel.");
gallons = [Link](dist);
[Link]("To go " + dist + " miles sportscar needs " +
gallons + " gallons of fuel.");
}
}

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.
class MyClass {
int x;
MyClass( int i) {
this.x = i;
}
}
class ConsDemo {
public static void main(String[ ] args) {
MyClass t1 = new MyClass(10);
MyClass t2 = new MyClass(88);
[Link](t1.x + " " + t2.x);
}
}
Output of the above code is 10 88
✓ this has some important uses. For example java syntax permits the name of a parameter or a local variable
to be the same of an instance variable. When this happens, the local name hides the instance variable.
The hidden instance variable can gain access by referring to it through this.

class MyClass {
int x;
MyClass( int x) {
x = x;
}
}
class ConsDemo {
public static void main(String[ ] args) {
MyClass t1 = new MyClass(10);
MyClass t2 = new MyClass(88);
[Link](t1.x + " " + t2.x);
}
}

Output is 0 0

JAtfA PROGRAMMING
If we use this key word we can gain access to the hidden instance variables
class MyClass {
int x;
MyClass( int x) {
this.x = x;
}
}

class ConsDemo {
public static void main(String[ ] args) {
MyClass t1 = new MyClass(10);
MyClass t2 = new MyClass(88);
[Link](t1.x + " " + t2.x);
}
}

O/P is 10 88

new OPERATOR REVISITED


✓ When you allocate an object, you use the following general form:
class-var = new classname ( );
✓ Now you can understand why the parentheses are needed after the class name. What is actually
happening is that the constructor for the class is being called.
✓ When you do not explicitly define a constructor for a class, then Java creates a default constructor for the
class.
✓ The default constructor automatically initializes all instance variables to zero. The default constructor is
often sufficient for simple classes, but it usually won’t do for more sophisticated ones.
✓ Once you define your own constructor, the default constructor is no longer used.

Garbage Collection
✓ Since objects are dynamically allocated by using the new operator, you might be wondering how such
objects are destroyed and their memory released for later reallocation. 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 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.
✓ Garbage collection only occurs sporadically (if at all) during the execution of your program. It will not occur
simply because one or more objects exist that are no longer used.
The finalize( ) Method
✓ Sometimes an object will need to perform some action when it is destroyed.
✓ To handle such situations, Java provides a mechanism 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.
✓ To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls that method
whenever it is about to recycle an object of that class. Inside the finalize( ) method, you will specify those
actions that must be performed before an object is destroyed.
✓ 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.

JAtfA PROGRAMMING
Access Modifiers:
✓ Encapsulation links data with the code that manipulates it. However, encapsulation provides another
important attribute: access control
✓ How a member can be accessed is determined by the access modifier attached to its declaration. Java
supplies a rich set of access modifiers.
✓ Java’s access modifiers 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 public, then that member can be accessed by any other code.
When a member of a class is specified as private, then that member can only be accessed by other
members of its class.
✓ When no access modifier is used, then by default the member of a class is public within its own package,
but cannot be accessed outside of its package.
✓ An access modifier precedes the rest of a member’s type specification. That is, it must begin a member’s
declaration statement. Here is an example:
public int i;
private double j;
private int myMethod(int a, char b) { //…
✓ To understand the effects of public and private access, consider the following program:
/* This program demonstrates the difference between public and private. */
class Test {
int a; // default access public
int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
class AccessTest {
public static void main(String args[ ]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
[Link](100); // OK
[Link]("a, b, and c: " + ob.a + " " +ob.b + " " + [Link]());
}
}

JAtfA PROGRAMMING
Pass objects to methods:
✓ It is possible to pass objects to a methods

// Objects can be passed to methods.


class Block {
int a, b, c;
int volume;
Block(int i, int j, int k) {
a = i;
b = j;
c = k;
volume = a * b * c;
}
// Return true if ob defines same block.
boolean sameBlock(Block ob) {
if((ob.a == a) & (ob.b == b) & (ob.c == c)) return
true; else return false;
}
// Return true if ob has same volume.
boolean sameVolume(Block ob) {
if([Link] == volume) return true;
else return false;
}
}
class PassOb {
public static void main(String[] args) {
Block ob1 = new Block(10, 2, 5);
Block ob2 = new Block(10, 2, 5);
Block ob3 = new Block(4, 5, 5);
[Link]("ob1 same dimensions as ob2: " + [Link](ob2));
[Link]("ob1 same dimensions as ob3: " + [Link](ob3));
[Link]("ob1 same volume as ob3: " + [Link](ob3));
}
}

JAtfA PROGRAMMING
How Arguments are passed:
✓ There are two ways to 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.
✓ When you pass a primitive type to a method, it is passed by value.
// Primitive types are passed by value.
class Test {
/* This method causes no change to the arguments
used in the call. */
void noChange(int i, int j) {
i = i + j;
j = -j;
}
}
class CallByValue {
public static void main(String[] args) {
Test ob = new Test();
int a = 15, b = 20;
[Link]("a and b before call: " + a + " " + b);
[Link](a, b);
[Link]("a and b after call: " + a + " " + b);
}
}
✓ When you pass an object to a method, objects are passed by call-by-reference.

// Objects are passed through their references.


class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
/* Pass an object. Now, ob.a and ob.b in object
used in the call will be changed. */
void change(Test ob)
{ ob.a = ob.a + ob.b;
ob.b = -ob.b;
}
}
class PassObjRef {
public static void main(String[] args) {
Test ob = new Test(15, 20);
[Link]("ob.a and ob.b before call: " + ob.a + " " + ob.b);
[Link](ob);
[Link]("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
}
JAtfA PROGRAMMING
Returning objects:
✓ A method can return any type of data, including class types that you create.
// Return a String object.
class ErrorMsg {
String[] msgs = { "Output Error", "Input Error", "Disk Full", "Index Out-Of-Bounds"};
// Return the error message.
String getErrorMsg(int i) {
if(i >=0 & i < [Link])
return msgs[i];
else
return "Invalid Error Code";
}
}
class ErrMsgDemo {
public static void main(String[] args) {
ErrorMsg err = new ErrorMsg();
[Link]([Link](2));
[Link]([Link](19));
}
}
O/P:
Disk Full
Invalid Error Code

✓ We can also return objects of classes that we create.


// Return a programmer-defined object. class
Err {
String msg; // error message
int severity; // code indicating severity of error
Err(String m, int s) {
msg = m;
severity = s;
}
}
class ErrorInfo {
String[] msgs = {
"Output Error",
"Input Error",
"Disk Full",
"Index Out-Of-Bounds"
};
int[] howbad = { 3, 3, 2, 4 };
Err getErrorInfo(int i) {
if(i >= 0 & i < [Link])
return new Err(msgs[i], howbad[i]);
else
return new Err("Invalid Error Code", 0);
}
}
class ErrInfoDemo {
public static void main(String[] args) {
ErrorInfo err = new ErrorInfo( );
Err e;
e = [Link](2);
[Link]([Link] + " severity: " + [Link]);
e = [Link](19);
[Link]([Link] + " severity: " + [Link]);
}
JAtfA PROGRAMMING
}

JAtfA PROGRAMMING
METHOD OVERLOADING:
✓ In Java it is possible to define two or more methods within the same class that share the same name, as
long as their parameter declarations are different. When this is the case, the methods are said to be
overloaded, and the process is referred to as method overloading.
✓ Method overloading is one of the ways that Java supports polymorphism.
✓ 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.
// Demonstrate method overloading. class
Overload {
void ovlDemo() {
[Link]("No parameters");
}
// Overload ovlDemo for one integer parameter.
void ovlDemo(int a) {
[Link]("One parameter: " + a);
}
// Overload ovlDemo for two integer parameters.
int ovlDemo(int a, int b) {
[Link]("Two parameters: " + a + " " + b);
return a + b;
}
// Overload ovlDemo for two double parameters.
double ovlDemo(double a, double b) {
[Link]("Two double parameters: " + a + " " + b);
return a + b;
}
}
class OverloadDemo {
public static void main(String[] args) {
Overload ob = new Overload();
int resI;
double resD;
// call all versions of ovlDemo()
[Link]();
[Link]();
[Link](2);
[Link]();
resI = [Link](4, 6);
[Link]("Result of [Link](4, 6): "
+resI); [Link]();
resD = [Link](1.1, 2.32);
[Link]("Result of [Link](1.1, 2.32): " +
resD);
}
}
O/P:
No parameters One
parameter: 2
Two parameters: 4 6
Result of [Link](4, 6): 10
Two double parameters: 1.1 2.32
JAtfA PROGRAMMING
Result of [Link](1.1, 2.32): 3.42

JAtfA PROGRAMMING
✓ The difference in their return types is insufficient for the purpose of overloading.
// one ovlDemo(int a) is ok
void ovlDemo(int a) {
[Link]("One parameter: " + a);
}
// Error. two ovlDemo(int a) are not ok even though their return types are different
int ovlDemo(int a) {
[Link]("One parameter: " + a);
return a *a;
}

✓ Java provides certain automatic type conversions. These conversions also apply to parameters of
overloaded methods. For example consider the following:

/* Automatic type conversions can affect overloaded method resolution. */


class Overload2
{ void f(int x) {
[Link]("Inside f(int): " + x);
}

void f(double x) {
[Link]("Inside f(double): " + x);
}
}

class TypeConv {
public static void main(String[ ] args) {
Overload2 ob = new Overload2();
int i = 10;
double d = 10.1;

byte b = 99;
short s = 10;
float f = 11.5F;

ob.f(i); // calls ob.f(int)


ob.f(d); // calls ob.f(double)

ob.f(b); // calls ob.f(int) - type conversion


ob.f(s); // calls ob.f(int) - type conversion
ob.f(f); // calls ob.f(double) - type conversion
}
}

O/P
Inside f(int) : 10
Inside f(double) : 10.1
Inside f(int) : 99
Inside f(int) : 10
Inside f(double) : 11.5

In the case of byte and short java automatically converts them to int. In the case of float the value
is converted to double and f(double) is called.

The automatic type conversions apply only if there is no direct match between a parameter and an
argument.

JAtfA PROGRAMMING
OVERLOADING CONSTRUCTORS:
✓ Like methods constructors can also be overloaded. This allows to construct objects in a variety of ways.
// Demonstrate an overloaded constructor.
class
MyClass{ int
x; MyClass()
{
[Link]("Inside MyClass().");
x = 0;
}
MyClass(int i) {
[Link]("Inside MyClass(int).");
x = i;
}
MyClass(double d) {
[Link]("Inside MyClass(double).");
x = (int) d;
}
MyClass(int i, int j) { [Link]("Inside
MyClass(int, int)."); x = i * j;
}
}
class OverloadConsDemo {
public static void main(String[] args) {
MyClass t1 = new MyClass(); O/P:
MyClass t2 = new MyClass(88); Inside MyClass(). Inside
MyClass t3 = new MyClass(17.23); MyClass(int).
MyClass t4 = new MyClass(2, 4); Inside MyClass(double).
[Link]("t1.x: " + t1.x); Inside MyClass(int, int). t1.x: 0
[Link]("t2.x: " + t2.x); t2.x: 88
[Link]("t3.x: " + t3.x); t3.x: 17
[Link]("t4.x: " + t4.x); t4.x: 8
}

// Initialize one object with another.


class Summation {
int sum;
// Construct from an int.
Summation(int num) {
sum = 0;
for(int i=1; i <= num; i++)
sum += i;
}
// Construct from another object.
Summation(Summation ob) {
sum = [Link];
}
}
class SumDemo {
public static void main(String[] args) {
Summation s1 = new Summation(5);
Summation s2 = new Summation(s1);
[Link]("[Link]: " + [Link]);
[Link]("[Link]: " + [Link]);
}
}
O/P:
JAtfA PROGRAMMING
[Link]: 15
[Link]: 15

JAtfA PROGRAMMING
UNDERSTANDING static:
✓ Normally, a class member must be accessed only in conjunction with an object of its class. However, it is
possible to create a member that can be used by itself, without reference to a specific instance.
✓ To create such a member, precede its declaration with the keyword 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.

static variables:
✓ Instance variables declared as static are, essentially, global variables. 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.

// Use a static variable.


class StaticDemo {
int x; // a normal instance variable
static int y; // a static variable
// Return the sum of the instance variable x and the static variable y.
int sum() {
return x + y;
}
}
class SDemo {
public static void main(String[] args) {
StaticDemo ob1 = new StaticDemo();
StaticDemo ob2 = new StaticDemo();
// Each object has its own copy of an instance variable.
ob1.x = 10;
ob2.x = 20;
[Link]("ob1.x: " + ob1.x + "\nob2.x: " + ob2.x);
[Link]();
StaticDemo.y = 19;
[Link]("[Link](): " + [Link]());
[Link]("[Link](): " + [Link]());
[Link]();
StaticDemo.y = 100;
[Link]("[Link](): " + [Link]());
[Link]("[Link](): " + [Link]());
[Link]();
}
}

O/P:
ob1.x: 10
ob2.x: 20

[Link](): 29
[Link](): 39

[Link](): 110
[Link](): 120

JAtfA PROGRAMMING
static Methods:
✓ Methods declared static are, essentially, global methods. They are called independently of any object.
Instead a static method is called through its class name.
✓ Methods declared as static have several restrictions:
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way.

// Use a static method. class


StaticMeth {
static int val = 1024; // a static variable
// A static method.
static int valDiv2() {
return val/2;
}
}
class SDemo2 {
public static void main(String[] args) {
[Link]("val is " + [Link]);
[Link]("StaticMeth.valDiv2(): " +StaticMeth.valDiv2());
[Link] = 4;
[Link]("val is " + [Link]);
[Link]("StaticMeth.valDiv2(): " + StaticMeth.valDiv2());
}
}
O/P:
val is 1024
StaticMeth.valDiv2(): 512
val is 4
StaticMeth.valDiv2(): 2

static Blocks:
✓ A static block is executed when the class is first loaded. Thus, it is executed before the class can be
used for any other purpose.

// Use a static block


class StaticBlock { static
double rootOf2; static
double rootOf3;
static {
[Link]("Inside static block.");
rootOf2 = [Link](2.0);
rootOf3 = [Link](3.0);
} O/P:
StaticBlock(String msg) { Inside static block.
[Link](msg); Inside Constructor
Square root of 2 is 1.4142135623730951
}
Square root of 3 is 1.7320508075688772
}
class SDemo3 {
public static void main(String[] args) {
StaticBlock ob = new StaticBlock("Inside Constructor");
[Link]("Square root of 2 is " +StaticBlock.rootOf2);
[Link]("Square root of 3 is " +StaticBlock.rootOf3);
}
JAtfA PROGRAMMING
}

JAtfA PROGRAMMING
NESTED AND INNER CLASSES:
✓ It is possible to define a class within another class; such classes are known as nested classes. The scope
of a nested class is bounded by the scope of its enclosing class. Thus, if class B is defined within class A,
then B does not exist independently of A.
✓ A nested class has access to the members, including private members, of the class in which it is nested.
However, the enclosing class does not have access to the members of the nested class.
✓ A nested class that is declared directly within its enclosing class scope is a member of its enclosing class.
It is also possible to declare a nested class that is local to a block.
✓ There are two types of nested classes: static and non-static.
✓ A static nested class is one that has the static modifier applied. Because it is static, it must access the
non-static members of its enclosing class through an object. That is, it cannot refer to non-static members
of its enclosing class directly.
✓ The most important type of nested class is the inner class. An inner class is a non-static nested class.
// Use an inner class. class
Outer {
int[] nums;
Outer(int[] n) {
nums = n;
}
void analyze() {
Inner inOb = new Inner();
[Link]("Minimum: " + [Link]());
[Link]("Maximum: " + [Link]());
[Link]("Average: " + [Link]());
}
// This is an inner class.
class Inner {
// Return the minimum value.
int min() {
int m = nums[0];
for(int i=1; i < [Link]; i++)
if(nums[i] < m) m = nums[i];
return m;
}
// Return the maximum value.
int max() {
int m = nums[0];
for(int i=1; i < [Link]; i++)
if(nums[i] > m) m = nums[i];
return m;
}
// Return the average.
int avg() {
int a = 0;
for(int i=0; i < [Link]; i++)
O/P:
a += nums[i];
Minimum: 1
return a / [Link];
Maximum: 9
}
Average: 5
}
}
class NestedClassDemo {
public static void main(String[] args) {
int[] x = { 3, 2, 1, 5, 6, 9, 7, 8 };
Outer outOb = new Outer(x);
[Link]();
}
}

JAtfA PROGRAMMING

You might also like