Classes and Objects: Unit 2
Classes and Objects: Unit 2
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box(); // creation of object
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
Or
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
// display volume of first box
mybox1.volume();
}
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.
Box(double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
Garbage Collection
• Since objects are dynamically allocated by using the new
operator, 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 for
you automatically.
• The technique that accomplishes this is called garbage
collection.
• It works like this: when no references to an object exist,
that object is assumed to be no longer needed, and the
memory occupied by the object can be reclaimed.
The finalize( ) Method
• Sometimes an object will need to perform some action when it is
destroyed. For example, if an object is holding some non-Java
resource such as a file handle or character font, then you might
want to make sure these resources are freed before an object is
destroyed.
• To handle such situations, Java provides a mechanism called
finalization
Box() {
width = -1; height = -1; depth = -1;
}
Box(double len) {
width = height = depth = len;
}}
class OverloadCons {
public static void main(String args[]) {
}
Using Objects as Parameters
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
} }
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
• Call by value
• Call by reference
• program
Returning objects
class change
{int c,x,y;
change(int a, int b)
{
x=a;
y=b;
}
change swap()
{
c=x;
x=y;
y=c;
return this;
}
}
public class Swap {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
change c=new change(5,10);
change c1;
System.out.println("value of a and b "+c.x+" "+c.y);
c1=c.swap();
Recursion
class Factorial {
// 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));
}
}
Access Control
• As you know, encapsulation links data with the
code that manipulates it.
• However, encapsulation provides another
important attribute: access control.
• Through encapsulation, you can control what
parts of a program can access the members of
a class.
• By controlling access, you can prevent misuse.
• How a member can be accessed is determined
by the access specifier that modifies its
declaration.
• Java’s access specifiers are public, private, and
protected.
• When a member of a class is modified by the
public specifier, 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 specifier is used, then by default
the member of a class is public within its own
package, but cannot be accessed outside of its
package.
• Eg:
• public int i;
• private double j;
• private int myMethod(int a, char b)
class Test {
int a; public int b; private int c;
// methods to access c
void setc(int i) { c = i; }
int getc() { return c;} }
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
ob.a = 10;
ob.b = 20;
// ob.c = 100; // Error!
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " +
ob.getc());
} }
Understanding static
• When a member is declared static, it can be
accessed before any objects of its class are
created, and without reference to any object. You
can declare both methods and variables to be
static.
• Methods declared as static have several
restrictions:
1. They can only call other static methods.
2. They must only access static data.
3. They cannot refer to this or super in any way.
// Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3; static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4; }
public static void main(String args[]) {
meth(42);
o/p
• Static block initialized.
• x = 42
• a=3
• b = 12
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
• Here is the output of this program:
• a = 42
• b = 99
Final
• A variable can be declared as final. Doing so
prevents its contents from being modified.
• This means that you must initialize a final variable
when it is declared. For example:
• final int FILE_NEW = 1;
• final int FILE_OPEN = 2;
• final int FILE_SAVE = 3;
• final int FILE_SAVEAS = 4;
• final int FILE_QUIT = 5;
• It is a common coding convention to choose
all uppercase identifiers for final variables.
• Variables declared as final do not occupy
memory .
• Final variable is essentially a constant
class StaticDemo {
final int a = 42;
final int b = 99;
void callme() {
// a++;
System.out.println("a = " + a);
}}
class Demo1 {
public static void main(String args[]) {
StaticDemo s = new StaticDemo();
s.callme();
}
}
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.
• 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
members of its enclosing class through an
object.
• The most important type of nested class is the
inner class.
• An inner class is a non-static nested class.
• It has access to all of the variables and
methods of its outer class and may refer to
them directly in the same way that other non-
static members of the outer class do.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner(); inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}}}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer(); outer.test(); } }
• You can, however, create an instance of Inner
outside of Outer by qualifying its name with
Outer, as in Outer.Inner.
• While nested classes are not applicable to all
stiuations, they are particularly helpful when
handling events
• Nested classes were not allowed by the
original 1.0 specification for Java. They were
added by Java 1.1..
Using Command-Line Arguments
• Sometimes you will want to pass information
into a program when you run it.
• This is accomplished by passing command-line
arguments to main( ).
• A command-line argument is the information
that directly follows the program’s name on
the command line when it is executed.
• The first command-line argument is stored at
args[0], the second at args[1], and so on.
class Demo1 {
public static void main(String args[]) {
int c=
Integer.parseInt(args[0])+Integer.parseInt(args[1])
;
System.out.println(c);
}
}
• Java Demo1 3 4
Exploring the String Class
• The first thing to understand about strings is that every
string you create is actually an object of type String.
• The second thing to understand about strings is that
objects of type String are immutable;
• once a String object is created, its contents cannot be
altered.
• To say that the strings within objects of type String are
unchangeable means that the contents of the String
instance cannot be changed after it has been created.
• However, a variable declared as a String reference can
be changed to point at some other String object at any
time.
for two reasons:
1. If you need to change a string, you can always
create a new one that contains the modifications.
2. Java defines a peer class of String, called
StringBuffer, and StringBuilder which allows
strings to be altered, so all of the normal string
manipulations are still available in Java.
• The String, StringBuffer, and StringBuilder
classes are defined in java.lang. Thus, they are
available to all programs automatically.
• boolean equals(String object)
• int length( )
• char charAt(int index)
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " +strOb1.length());
System.out.println(strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
}}
class StringDemo3 {
public static void main(String args[]) {
String str[] = { "one", "two", "three" };
for(int i=0; i<str.length; i++)
System.out.println("str[" + i + "]: " +str[i]);
}
}
The String Constructors
• String s = new String();
//will create an instance of String with no
characters in it.
• String(char chars[ ])
//To create a String initialized by an array
of characters
Eg : char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
• String(char chars[ ], int startIndex, int numChars)
Eg: char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
String(String strObj)
Eg:
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Eg:
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
Special String Operations
• String Literals
• String Concatenation
• String Concatenation with Other Data Types
String Literals
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // use string literal
System.out.println(s2);
String Concatenation
• class ConCat {
• public static void main(String args[]) {
• String longStr = “I like " +”java”
• System.out.println(longStr);
• }
• }
String Concatenation with Other Data
Types
• int age = "9";
• String s = "He is " + age + " years old.";
• System.out.println(s);
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}}
String Comparison
• equals( ) and equalsIgnoreCase( )
• startsWith( ) and endsWith( )
equals( ) and equalsIgnoreCase( )
• boolean equals(Object str)
• boolean equalsIgnoreCase(String str)
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s4 = "HELLO";
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s4));
System.out.println(s1.equalsIgnoreCase(s4));
}
}
• boolean startsWith(String str)
• boolean endsWith(String str)
– Eg : "Foobar".endsWith("bar")
– "Foobar".startsWith("Foo")
• boolean startsWith(String str, int startIndex)
– Eg: "Foobar".startsWith("bar", 3)
equals( ) Versus ==
• the equals( ) method compares the characters
inside a String object.
• The == operator compares two object
references to see whether they refer to the
same instance.
• public static void main(String args[]) {
• String s1 = "Hello";
• String s2 = new String(s1);
• System.out.println(equals(s2));
• System.out.println(s1 == s2);
• }
compareTo( )
• int compareTo(String str)
public static void main(String args[])
{
System.out.println("a".compareTo("b"));
}
o/p: -1
class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country” };
public static void main(String args[]) {
for(int j = 0; j < arr.length; j++) {
for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}} System.out.println(arr[j]); }}}
o/p:
• Now
• aid
• all
• come
• country
• for
• good
• is
• men
• of
• the
• the
• their
• time
• to
• to
• int compareToIgnoreCase(String str)
Searching Strings
• indexOf( ) Searches for the first occurrence of
a character or substring.
• lastIndexOf( ) Searches for the last occurrence
of a character or substring.
int indexOf(int ch)- To search for the last occurrence of a character
int lastIndexOf(int ch)
String s1 = "one";
String s2 = s1.concat("two"); or
String s1 = "one";
String s2 = s1 + "two";
• replace( )
String replace(char original, char replacement)
String replace(CharSequence original, CharSequence
replacement)
Eg
String s = "Hello".replace('l', 'w');
System.out.println(s)
100
I/O Stream Fundamentals
• A stream is a sequence of data.
A source stream initiates the flow of data, also called
an input stream.
• A destination stream terminates the flow of data, also
called an output stream.
•input stream can abstract many different kinds of
input: from a disk file, a keyboard, or a network
socket.
•output stream may refer to the console, a disk
file, or a network connection.
• java.io package.
101
Fundamental Stream Classes
Stream Byte Streams Character Streams
102
• Java defines two types of streams: byte and character.
• Byte streams provide a convenient means for handling
input and output of bytes.
• Byte streams are used, for example, when reading or
writing binary data.
• Character streams provide a convenient means for
handling input and output of characters. They use
Unicode and, therefore, can be internationalized.
• Also, in some cases, character streams are more
efficient than byte streams.
103
The Byte Stream Classes
• Byte streams are defined by using two class
hierarchies. At the top are two abstract
classes:
• InputStream and OutputStream.
104
The InputStream Methods
• The three basic read methods are:
1. int read()
2. int read(byte[] buffer)
3. int read(byte[] buffer, int offset, int length)
• Other methods include:
1. void close()
2. int available()
3. long skip(long n)
4. boolean markSupported()
5. void mark(int readlimit)
6. void reset()
105
The OutputStream Methods
• The three basic write methods are:
1. void write(int c)
2. void write(byte[] buffer)
3. void write(byte[] buffer, int offset, int
length)
• Other methods include:
1. void close()
2. void flush()
106
The Character Stream Classes
• At the top are two abstract classes, Reader
and Writer.
107
The Reader Methods
• The three basic read methods are:
1. int read()
2. int read(char[] cbuf)
3. int read(char[] cbuf, int offset, int length)
• Other methods include:
1. void close()
2. boolean ready()
3. long skip(long n)
4. boolean markSupported()
5. void mark(int readAheadLimit)
6. void reset()
108
The Writer Methods
• The basic write methods are:
1. void write(int c)
2. void write(char[] cbuf)
3. void write(char[] cbuf, int offset, int length)
4. void write(String string)
5. void write(String string, int offset, int length)
• Other methods include:
1. void close()
2. void flush()
109
110
111
Node Streams
Type Character Streams Byte Streams
112
Reading Console Input
113
In Java, console input is accomplished by reading from System.in.
To obtain a character-based stream that is attached to the console,wrap System.in in a
BufferedReader object, to create a character stream.
BuffereredReader supports a buffered input stream.
Its most commonly used constructor is shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being
created.
Reader is an abstract class. One of its concrete subclasses is
InputStreamReader, which converts bytes to characters.
115
To obtain an InputStreamReader object that is linked to System.in, use the following
constructor:
InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for inputStream.
Putting it all together, the following line of code creates a BufferedReader that is connected
to the keyboard:
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
After this statement executes, br is a character-based stream that is linked to the console
through System.in.
116
Reading Characters
To read a character from a BufferedReader, use read( ).
The version of read( ) that we will be using is
int read( ) throws IOException
Reading Strings
To read a string from the keyboard, use the version of
readLine( ) that is a member of the BufferedReader class. Its
general form is shown here:
String readLine( ) throws IOException
117
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
118
• Here is a sample run:
• Enter characters, 'q' to quit.
• 123abcq
• 1
• 2
• 3
• a
• b
• c
• q
119
import java.io.*;
class BRReadLines {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop")); } }
120
Writing Console Output
121
Console output is most easily accomplished with print( ) and println( )
These methods are defined by the class PrintStream(which is the type of the object
referenced by System.out)
PrintStream is an output stream derived from OutputStream, it also implements the low-
level method write( ).
Thus, write( ) can be used to write to the console.
The simplest form of write( ) defined by PrintStream is shown here:
void write(int byteval)
This method writes to the stream the byte specified by byteval. Although byteval is
declared as an integer, only the low-order eight bits are written.
122
// Demonstrate System.out.write().
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
123
Reading and Writing Files
124
Two of the most often-used stream classes are FileInputStream and FileOutputStream, which
create byte streams linked to files.
To open a file, create an object of one of these classes, specifying the name of the file as an
argument to the constructor. FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
Here, fileName specifies the name of the file to open.
When we create an input stream/output stream , if the file does not exist, then
FileNotFoundException is thrown in both case.
When an output file is opened, any preexisting file by the same name is destroyed.
125
When we are done with a file, we should close it by calling close( ).
It is defined by both FileInputStream and FileOutputStream, as shown here:
void close( ) throws IOException
To read from a file, a version of read( ) that is defined within
FileInputStream.
The one that we will use is shown here:
int read( ) throws IOException
Each time that it is called, it reads a single byte from the file and returns the byte as an
integer value.
read( ) returns –1 when the end of the file is encountered. It can throw an IOException.
126
import java.io.*;
class ShowFile {
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
try { fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("File Not Found");
} // read characters until EOF is encountered
do { i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);fin.close();}}
127
java TestNodeStreams file1
128
• void write(int byteval) throws IOException
129
import java.io.*;
class CopyFile {
public static void main(String args[])throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
try {
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("Input File Not Found");
return;
}
130
try {
fout = new FileOutputStream(args[1]);
} catch(FileNotFoundException e) {
System.out.println("Error Opening Output File");
return;
}
}
131
try {
do {
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
} catch(IOException e) {
System.out.println("File Error");
}
fin.close();
fout.close();
}
}
132
NIO.2
• There is no single operation to copy a file to another
location. When necessary, it has to be implemented using
data flows.
• Support to file attributes (creation date, last update date,
permissions to read/write, executable flag, etc.) is limited;
• It's not 100% consistent throughout the different platforms
supported by Java;
• Often, exceptions thrown due to failures during file
operations are not very useful;
• It's not possible to extend the API to support a new type of
file system.
• to address these limitations, JSR 203 – More New
I/O APIs for the JavaTM Platform (“NIO.2”) was
proposed.
• This extension was called “NIO.2” because since
Java 1.4 the package java.nio is already present,
supporting the creation of I/O channels.
• Channels are objects that represent a connection
with a generic resource that is capable of
executing I/O operations, such as files and
network sockets.
The NIO.2 API adds three subpackages to java.nio:
• java.nio.file: main package for NIO.2, defines
interfaces and classes to access files and file
systems using the new API;
• java.nio.file.attribute: contains classes and
interfaces related to reading and changing file
attributes;
• java.nio.file.spi: contains service provider
interfaces for NIO.2, to be used by developers who
wish the implement support to a new type of file
system.