Java II Unit 2020
Java II Unit 2020
Inheritance
Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another. With the use of inheritance the
information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).
Types of inheritance:
1
1. Single Inheritance : In single inheritance, subclasses inherit the features of
one superclass. In image below, the class A serves as a base class for the
derived class B.
2
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
3
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
The output from this program is shown here:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
4
{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
classTestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
5
Program for Hierarchical Inheritance:
class A
{
private void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
//All classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
Output:
6
method of Class A
method of Class A
method of Class A
class A{
void msg(){System.out.println("Hello");}
7
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
output:
Compile by: javac C.java
java:7: error: '{' expected
class C extends A,B{//suppose if it were
^
1 error
8
Program for Hybrid Inheritance:
public class A
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class B extends A
{
public void show()
{
System.out.println("show() method of ClassB");
}
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class C extends A
{
public void show()
{
System.out.println("show() method of ClassC");
}
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class D extends B,C
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
public static void main(String args[])
{
ClassD d = new ClassD();
d.dispD();
d.show();//Confusion happens here which show method to call
9
}}
Output :
Error!!
public
default
protected
private
public
The member with public modifiers can be accessed by any classes. The public
methods, variables or class have the widest scope.
default
protected
The protected modifier is used within same package. It lies between public and
default access modifier. It can be accessed outside the package but through
inheritance only.
A class cannot be protected.
private
The private methods, variables and constructor are not accessible to any other
class. It is the most restrictive access modifier. A class except a nested class
cannot be private.
Methods declared public in a superclass also must be public in all subclasses.
10
Methods declared protected in a superclass must either be protected or public
in subclasses; they cannot be private.
Methods declared private are not inherited at all, so there is no rule for them.
Private Example:
Addition.java
11
package abcpackage;
public class Addition {
Test.java
package xyzpackage;
import abcpackage.*;
class Test extends Addition{
public static void main(String args[]){
Test obj = new Test();
System.out.println(obj.addTwoNumbers(11, 22));
}
}
Output:
33
12
Different package non- No No No yes
subclass
Forms of Inheritance
The choices between inheritance and overriding, subclass and subtypes, mean
that inheritance can be used in a variety of different ways and for different
purposes. Many of these types of inheritance are given their own special
names. We will describe some of these specialized forms of inheritance.
Specialization
Specification
Construction
Generalization or Extension
Limitation
Combination
Specialization Inheritance
By far the most common form of inheritance is for specialization.
A good example is the Java hierarchy of Graphical components in the AWT:
Component
o Label
o Button
o TextComponent
TextArea
TextField
o CheckBox
o ScrollBar
Each child class overrides a method inherited from the parent in order to
specialize the class in some way.
Specification Inheritance
13
ActionListener, MouseListener, and so on specify behaviour, but must be
subclassed.
If the parent class is used as a source for behavior, but the child class has no
is-a relationship to the parent, then we say the child class is using inheritance
for construction.
An example might be subclassing the idea of a Set from an existing List class.
Generally not a good idea, since it can break the principle of substituability,
but nevertheless sometimes found in practice. (More often in dynamically typed
languages, such as Smalltalk).
If a child class overrides a method inherited from the parent in a way that
makes it unusable (for example, issues an error message), then we call it
inheritance for limitation.
For example, you have an existing List data type that allows items to be
inserted at either end, and you override methods allowing insertion at one end
in order to create a Stack.
Generally not a good idea, since it breaks the idea of substitution. But again, it
is sometimes found in practice.
combination
Two or more classes that seem to be related, but its not clear who should be
the parent and who should be the child.
Example: Mouse and TouchPad and JoyStick
Better solution, abstract out common parts to new parent class, and use
subclassing for specialization.
Benefits of Inheritance
Cost of Inheritance
Execution speed
Program size
Message Passing Overhead
Program Complexity (in overuse of inheritance)
This does not mean you should not use inheritance, but rather than you must
understand the benefits, and weigh the benefits against the costs.
polymorphism
Adhoc polymorphism
Adhoc polymorphism refers to polymorphic functions that can be applied to
different argument types known by the same name in a programming
language. Adhoc polymorphism is also known as function overloading or
operator overloading because a polymorphic function can represent a number
of unique and potentially heterogeneous implementations depending on the
type of argument it is applied to.
Adhoc polymorphism defines operators that can be used for different argument
types. It follows a dispatch mechanism in which the control moving from one
named function is dispatched to several other functions without specifying the
function being called. This function overloading permits multiple functions
15
taking different argument types to be known by the same name as the compiler
and interpreter calls the right function.
int a, b;
float x, y;
String s1=”hello”;
String s2=”world”;
The symbol ‘+’ is used in two different ways. In the expression a+b, it stands for
the function that adds two integers. In the expression x+y, it stands for the
function that adds two floats. In the concatenation of two strings, we are using
‘+’ .
Thus, ad hoc polymorphism refers to the use of a single function name to
indicate two or more unique functions. The compiler decides which function to
call depending on the type of arguments.
Pure polymorphism:
Pure Polymorphism is a single function can be applied to arguments of a variety of types.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many
forms.
There are two types of polymorphism in java: compile time polymorphism and
runtime polymorphism.
Method overriding: This allows us to have more than one method having the same
name, if the parameters of methods are same in number, sequence and data types of
parameters.
Example1:
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}
Example2:
class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
17
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
Output:
drawing rectangle...
drawing circle...
drawing triangle...
18
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
Output:
a: 10
a and b: 10,20
double a: 5.5
O/P : 30.25
Packages in Java
Built-in Packages:
These packages consists of a large number of classes which are a part of Java
API.
For e.g: we have used java.io package previously which contain classes to
support input / output operations in Java. Similarly, there are other packages
which provides different functionality.
19
Some of the commonly used built-in packages are shown in the table below :
Package
Description
Name
Contains language support classes ( fore.g classes which defines
java.lang primitive data types, math operations, etc.) . This package is
automatically imported.
java.io Contains classes for supporting input / output operations.
Contains utility classes which implement data structures like
java.util Linked List, Hash Table, Dictionary, etc and support for Date /
Time operations.
java.applet Contains classes for creating Applets.
Contains classes for implementing the components of graphical
java.awt
user interface ( like buttons, menus, etc. ).
java.net Contains classes for supporting networking operations.
User-defined packages:
Creating a Package:
While creating a package, you should choose a name for the package and
include a package statement along with that name at the top of every
source file that contains the classes, interfaces, enumerations, and
annotation types that you want to include in the package.
forExample: packageMypack;
The package statement should be the first line in the source file. There can be
only one package statement in each source file, and it applies to all types in the
file.
To compile the Java programs with package statements, you have to use -d
option as shown below.
20
javac -d Destination_folder file_name.java
You need to use fully qualified name e.g. mypack.Simpleetc to run the class.
Compile:javac -d .file_name.java
Run:java mypack.file_name
Importing Packages
importpkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subordinate package inside the outer package separated by a dot (.).
There is no practical limit on the depth of a package hierarchy, except that
imposed by the file system.
either an explicit classname or a star (*), which indicates that the Java
compiler should import the entire package.
ForExample:
import java.util.Scanner;
import java.io.*;
The basic language functions are stored in a package inside of the java
package called java.lang. (Default Package)
This is equivalent to the following line being at the top of all of your
programs:
Import java.lang.*;
There are three ways to access the package from outside the package.
import package.*;
import package.classname;
fully qualified name.
21
//save by A.java
If you import package.classname
package pack; then only declared class of this
public class A{ package will be accessible.
public void msg() //save by A.java
{System.out.println("Hello");} package pack;
}
public class A
//save by B.java {
public void msg()
package mypack; {System.out.println("Hello");} }
import pack.*;
//save by B.java
class B{
public static void main(String package mypack;
args[]){ import pack.A;
A obj = new A();
obj.msg(); class B{
} } public static void main(String a
rgs[]){
A obj = new A();
Complile: javac –d . obj.msg();
B.java //(Because MainMethod }
occurs at B.java) }
Run: java
pack.B //(Because Output:Hello
MainMethod occurs at B.java)
Output:Hello
Interfaces
Defining an Interface
22
Along with abstract methods, an interface may also contain constants,
default methods, static methods, and nested types.
Method bodies exist only for default methods and static methods.
Syntax:
access_specifier interface name {
return-type method-name (parameter-list); //Abstract Method
type final-varname1 = value;
type final-varname2 = value; //variables
default method-name (parameter-list)
{ //default method body; }
staticmethod-name (parameter-list)
{ //method body }
}
In other words, Interface fields are public, static and final by default, and the
methods are public and abstract.
Implementing Interfaces
Once an interface has been defined, one or more classes can inherit that
interface by using implements Keyword
Syntax:
If a class implements more than one interface, the interfaces are separated
with a comma.
As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.
23
Nested Interfaces
class A {
// this is a nested interface
public interface NestedIF {
boolean isNotNegative(int x);
}
}
// B implements the nested interface.
class B implements A.NestedIF { //nested interface Declaration
public boolean isNotNegative(int x)
{
return x < 0 ? false : true;
}
}
class NestedIFDemo {
public static void main(String args[]) {
24
A.NestedIF nif = new B(); // use a nested interface
reference
if(nif.isNotNegative(10))
{
System.out.println("10 is not negative");
}
if(nif.isNotNegative(-12))
{
System.out.println("this won't be displayed");
}
}
}
Note:
Notice that A defines a member interface called NestedIF and that it is
declared public. Next, B implements the nested interface by specifying
implements A.NestedIF
Notice that the name is fully qualified by the enclosing class name. Inside the
main( ) method, an A.NestedIF reference called nif is created, and it is
assigned a reference to a B object. Because B implements A.NestedIF, this is
legal.
Applying Interfaces
used to achieve abstraction.
//Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. g
etDrawable()
d.draw();
}}
Output:
drawing circle
25
Multiple inheritance in Java by interface
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7
{
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}
26
}
Output:Hello Welcome
Interface inheritance
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
Output:
Hello
Welcome
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
27
Output:
drawing rectangle
default method
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
Output:
drawing rectangle
27
Difference between abstract class and interface
28
implements?.
8) A Java abstract class can have class Members of a Java interface are
members like private, protected, etc. public by default.
9)Example:
public abstract class Shape{
public abstract void draw(); Example:
public void display() public interface Drawable{
{ void draw();
System.out.println(“display method”); }
}
}
Java I/O (Input and Output) is used to process the input and produce the
output.
Java uses the concept of a stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
Streams
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java. In general, a stream means
continuous flow of data. Streams are clean way to deal with input/output without
having every part of your code understand the physical.
In Java, 3 streams are created for us automatically. All these streams are
attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
1. ByteStreams
29
2. CharacterStreams
Constructor Description
File(File parent, String It creates a new File instance from a parent abstract
child) pathname and a child pathname string.
It creates a new File instance by converting the given
File(String pathname)
pathname string into an abstract pathname.
File(String parent, It creates a new File instance from a parent pathname
String child) string and a child pathname string.
It creates a new File instance by converting the given file:
File(URI uri)
URI into an abstract pathname.
Syntax(Constructors):
For example:
30
File f1 = new File("/");
File f2 = new File("/","abc.txt");
File f3 = new File(f1,"abc.txt");
File defines many methods that obtain the standard properties of a File object.
// Demonstrate File.
import java.io.File;
class FileDemo {
static void p(String s) {
System.out.println(s);
}
public static void main(String args[]) {
File f1 = new File("/java/COPYRIGHT");
p("File Name: " + f1.getName());
p("Path: " + f1.getPath());
p("Abs Path: " + f1.getAbsolutePath());
p("Parent: " + f1.getParent());
p(f1.exists() ? "exists" : "does not exist");
p(f1.canWrite() ? "is writeable" : "is not writeable");
p(f1.canRead() ? "is readable" : "is not readable");
p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
p(f1.isFile() ? "is normal file" : "might be a named pipe");
p(f1.isAbsolute() ? "is absolute" : "is not absolute");
p("File last modified: " + f1.lastModified());
p("File size: " + f1.length() + " Bytes");
}
}
Output:
31
File Name: COPYRIGHT
Path: /java/COPYRIGHT
Abs Path: /java/COPYRIGHT
Parent: /java
exists
is writeable
is readable
is not a directory
is normal file
is absolute
File last modified: 812465204000
File size: 695 Bytes
Byte Streams:
A Byte stream will read a file Byte by Byte.
Byte stream is defined by using two abstract class at the top of hierarchy,
they are InputStream and OutputStream.
32
Java byte streams are used to perform input and output of 8-bit bytes.
Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.
These two abstract classes have several concrete classes that handle
various devices such as disk files, network connection etc.
These classes define several key methods. The most important are
33
1. read() : reads byte of data.
2. write() : Writes byte of data.
3. close(): to close allConnections.
FileInputStream Class
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-
oriented data (streams of raw bytes) such as image data, audio, video etc. You can also
read character-stream data.
Syntax:
FileInputStream(String filepath)
FileInputStream(File fileObj)
forExample:
FileInputStream f0 = new FileInputStream("abc.txt")
or
File f = new File("abc.txt");
FileInputStream f1 = new FileInputStream(f);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Output: W
read all characters:
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
34
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Output: Welcome to java
FileOutputStream Class:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
They can throw a FileNotFoundException. Here, filePathis the full path name of a
file, and fileObj is a File object that describes the file. If append is true, the file is
opened in append mode.
write byte:
import java.io.FileOutputStream;
35
public class writestring {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to JAVA.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
import java.io.*;
public class CopyFile{
try{
in=new FileInputStream("input.txt");
out=new FileOutputStream("output.txt");
int c;
while((c =in.read())!=-1){
out.write(c);
}
}finally{
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
}
}
}
BufferedInputStream class BufferedOutputStream class
Java BufferedInputStream class is used Java BufferedOutputStream class is
to read information from stream. It used for buffering an output stream. It
internally uses buffer mechanism to internally uses buffer to store data. It
make the performance fast. adds more efficiency than to write data
36
directly into a stream. So, it makes the
performance fast.
Syntax: Syntax:
BufferedInputStream(InputStream BufferedOutputStream(OutputStream
inputStream) outputStream)
or or
BufferedInputStream(InputStream BufferedOutputStream(OutputStream
inputStream, int bufSize) outputStream, intbufSize)
Java Byte streams are used to perform input and output of 8-bit bytes,
whereas Java Character streams are used to perform input and output for 16-
37
bit unicode. Though there are many classes related to character streams but
the most frequently used classes are, FileReader and FileWriter.
Character stream is also defined by using two abstract class at the top of
hierarchy, they are Reader and Writer.
Reader
Reader is an abstract class that defines Java’s model of streaming character input. It
implements the Closeable and Readable interfaces. All of the methods in this class
(except for markSupported( )) will throw an IOException on error conditions.
Writer
Writer is an abstract class that defines streaming character output. It implements the
Closeable, Flushable, and Appendable interfaces. All of the methods in this class
throw an IOException in the case of errors.
These two abstract classes have several concrete classes that handle unicode
character.
38
FileWriter Output stream that writes to file.
FilterReader
Filtered reader
FileReader Class
Java FileReader class is used to read data from the file. It returns data in byte format
like FileInputStream class. It is character-oriented class which is used for file handling
in java.
Syntax:
FileReader(String filePath)
FileReader(File fileObj)
Either can throw a FileNotFoundException. Here, filePathis the full path name of a
file, and fileObjis a File object that describes the file.
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to JAVA.
39
Output:
Welcome to JAVA.
FileWriter Class
Syntax:
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to JAVA.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
Output: Success...
testout.txt: Welcome to JAVA.
Copying From one File to another by using FileReader and FileWriter classes:
import java.io.*;
public class CopyFile{
try{
in=new FileReader("input.txt");
out=new FileWriter("output.txt");
40
int c;
while((c =in.read())!=-1){
out.write(c);
}
}finally{
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
}
}
}
41
BufferedReaderbr=new BufferedWriter buffer = new
BufferedReader(fr); BufferedWriter(writer);
buffer.write("Welcome to JAVA.");
inti; buffer.close();
while((i=br.read())!=-1){ System.out.println("Success");
System.out.print((char)i); }
} }
br.close();
fr.close();
}
}
Output: Output:
Welcome to JAVA. success
In Java, there are three different ways for reading input from the user in the command
line environment(console).
This is probably the most preferred method to take input. The main purpose of the Scanner class is to
parse primitive types and strings using regular expressions, however it is also can be used to read input
from the user in the command line.
I mport java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string "+s);
int a = in.nextInt();
System.out.println("You entered integer "+a);
42
float b = in.nextFloat();
System.out.println("You entered float "+b);
}
}
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.
To obtain an InputStreamReader object that is linked to System.in, use the following
constructor:
InputStreamReader(InputStreaminputStream)
43
text until you enter the word “stop”:
Java SE 6 adds the Console class. It is used to read from and write to
the console, if one exists.
Console is primarily a convenience class because most of its
functionality is available through System.in and System.out.
Syntax:
44
Console supplies no constructors. Instead, a Console object is obtained by
calling System.console( ), which is shown here:
str = con.readLine("Enter a string: ");// Read a string and then display it.
System.out.println(str);
}
}
RandomAccessFile
RandomAccessFile encapsulates a random-access file. It is not derived
from InputStream or OutputStream.
Instead, it implements the interfaces DataInput and DataOutput, which
define the basic I/O methods. It also implements the Closeable interface.
RandomAccessFile is special because it supports positioning requests—
that is, you can position the file pointer within the file.
Syntax:
It has these two constructors:
RandomAccessFile(File fileObj, String access)
throws FileNotFoundException
or
RandomAccessFile(String filename, String access)
hrows FileNotFoundException
herefileObjspecifies the name of the file to open as a File object.
In the second form, the name of the file is passed in filename.
45
In both cases, access determines what type of file access is permitted.
File Access parameter as:
If it is “r”, then the file can be read, but not written.
If it is “rw”, then the file is opened in read-write mode.
The method seek( ), shown here, is used to set the current position of the
file pointer within the file:
}
}
46