Professional Documents
Culture Documents
• Introduction of java
• Java Virtual Machine
• Java system overview /Java compile-time Environment
• Java Buzzwords
• Difference between C++ and JAVA
Introduction of java
• Java was developed by Jems Goslin at Sun Microsystems in
the early 1990’s.
• The world wide web appeared in 1993, the language has been
enhanced to facilitate programming on web.
• Since then it become one of the most popular language for
web.
• This language was initially called “Oak” but renamed as java in
1995.
• The primary motivation was the need of platform-independent
language that could be used to create software to be
embedded in various customer electronic devices, such as
microwave ovens and remote controls.
• Java never provides any tool to handle operations related to
memory.
• The memory addressing is implemented and controlled by java
virtual machine (JVM).
• Memory addressing mean where the variables are created,
objects are stored, and methods are stored in memory.
Introduction of java
• Java is derived from c++, because most of the
features are taken from c++.
• Sun released the first JDK 1.0 in 1995.
• It promised a platform independent language to
the programmer.
• it was ‘write Once Run anywhere’.
• Sun launched different versions for different
purposes, e.g. J2EE is enterprise edition, use for
server side programming, J2ME is micro edition
used for mobile applications, and J2SE is for
standard edition.
• Introduction of wrapper class makes java a
complete OOP language.
• When a java source file is compiled, a class file
is generated, which is a collection of Byte codes.
Byte codes are portable. These are later
changed to native code by JVM.
• Bytes code are least affected by virus as
compared by executable files. If the Byte code is
affected, these are recognized by the JVM and
not allowed to be executed.
• Java has built-in support for exception handling.
• It has built-in support for multithreading
application development.
• There is a built-in support for networking.
Java Virtual Machine
• JVM system is an interpreter.
• Java virtual machine is a software system that translates and execute java
byte code.
– An instruction set and the meaning of those instructions – the byte codes
– A binary format – the class file format
– An algorithm to verify the class file
Java PC Native
Method Area Heap method
Stacks Registers
Stacks
Runtime data areas
Java Just in
Java Interprete Time
Byte codes r Compiler Java
move locally Virtual
or through machine
Java network
Compiler
Runtime System
Java
Bytecod Operating System
e
(.class )
Hardware
Java compile-time Environment
• Interpreted
– java compiler generate byte-codes, not native
machine code
– The compiled byte-codes are platform-independent
– java byte codes are translated on the fly to machine
readable instructions in runtime (Java Virtual
Machine)
• Portable
– same application runs on all platforms
– The sizes of the primitive data types are always the
same.
– The libraries define portable interfaces
Cont….
• Reliable
– Extensive compile-time and runtime error checking.
– No pointers but real arrays. Memory corruptions or
unauthorized memory accesses are impossible.
– Automatic garbage collection tracks objects usage over
time.
• Secure
The Java language is secure in that it is very difficult to write incorrect
code or viruses that can corrupt/steal your data, or harm hardware such
as hard disks.
– No pointer arithmetic
• Garbage collection
• Array bounds checking
• No illegal data conversions
• Browser level (applies to applets only):
• No local file I/O
Java achieved protection by confining an applet to java execution
environment and not allowing it access to other parts of the computer.
• Multithreaded
Public is access specifier then that member may be accessed by code out
side the class in which it is declared.
• Static allows main to be called without having to instantiate a
particular instance of the class. This is necessary since main() is
called by JVM before any objects are made.
• void simply tells the compiler that main() does not return a
value.
• main() is the method called when a java application begins.
• String args [] declares a parameter named args, which is an
array of instances of the class string.
• Objects of type string store character strings. In this case
args receives any command-line arguments present when a
program is executed.
• System.out.println (“This is a simple Java program”);
– If you want to use classes in another library, you say import and
the name of the library.
– There are no preprocessor-like macros.
– There is no conditional compiling (#ifdef)
JAVA vs C++
• All the primitive types in Java have specified sizes that
are machine independent for portability.
– On some systems this leads to non-optimized performance
– The char type uses the international 16-bit Unicode character
set, so it can automatically represent most national characters.
– There’s a read-only length member that tells you how big the array
is, and run-time checking throws an exception if you go out of
bounds.
– All arrays are created on the heap, and you can assign one array to
another (the array handle is simply copied).
• There is a garbage collection in JAVA
– Garbage collection means memory leaks are much harder to cause
in Java, but not impossible. (If you make native method calls that
allocate storage, these are typically not tracked by the garbage
collector.)
– The garbage collector is a huge improvement over C++, and makes
a lot of programming problems simply vanish. It might make Java
unsuitable for solving a small subset of problems that cannot
tolerate a garbage collector, but the advantage of a garbage
collector seems to greatly outweigh this potential drawback.
JAVA vs C++
• There are no destructors in Java.
• 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.
• 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, since it is defined
as having its high byte first
• 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.
In addition to other uses, variables of type int are commonly
employed to control loops and to index arrays.
• Long
6556 1 2 3
Examples:
int[] fibonacci = {1, 1, 2, 3, 5, 8, 13, 21, 34};
String[] cats = {“bug”, “squeaky”, “paris”, “kitty
kat”};
int[] unit = {1};
Constant Arrays
• As in other declarations, the modifier final can be applied in an array
declaration. The modifier has the usual effect – after its initialization,
the array variable is treated as a constant. In this case, the array
variable cannot change which array it references, however, the values in
the array can be changed!
final int[] B = {10, 20};
• Graphically this would look like the following:
10 20
B
class CopyArrays
{
public static void main (String [] args)
{
int[] Array1 = {1, 2, 3, 4};
int[] Array2 = {5, 6, 7, 8};
copy (Array1, Array2);
for (int i=0; i< Array1.length; i++)
System.out.println(Array1[i] + " ");
System.out.flush();
for (int i=0; i< Array2.length; i++)
System.out.print (Array2[i] + " ");
System.out.flush();
}
public static void copy (int[] x, int[] y)
{
for (int i=0; i<x.length;i++)
y[i]=x[i];
}
}
Multi-Dimensional Array
• Multi-dimensional arrays are actually array of arrays. It is like a
pointer to an array of pointers.
• Two-Dimensional Array
Syntax:
datatype [ ][ ] variable=new type[n][m];
int [ ][ ] town= new int [3][3];
Heap
1000 6556
Stack
6556
Town[0][0] Town[0][1] Town[0][2]
Town[0
Town ]
96656
1000
1000 Town[1 96656
]
13665
Town[2
]
13665
class demo
{
public static void main(String args[])
{
int [] [] town= new int [4] [];
system.out.println(town[0]);
system.out.println(town[1]);
system.out.println(town[2]);
}}
Output:
Null
Null
Null
two-dimensional array
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 0 000
0 2 468
0 4 8 12 16
0 6 12 18 24
Arrays
• Advantages
– Very efficient, quick to access and add to
– Type-safe, can only add items that match the
declared type of the array
• Disadvantages
– Fixed size, some overhead in copying/resizing
– Can’t tell how many items in the array, just how large
it was declared to be
– Limited functionality, need more general functionality
Reading strings using BufferedReader
• Recall from our earlier look at using
BufferedReader that we need to first declare
a BufferedReader object that was directed to
read from the input stream attached to the
standard input device. Once this is done,
reading strings from the keyboard is
straightforward.
//output results
System.out.println(“Word “ + word + “ has a length of “
+ wordLength + “ characters.”);
}
}
Palindrome Example
//Checks words to see if they are palindromes
import java.io.*;
if (isPalindrome(s))
System.out.println(s + " is a palindrome");
else
System.out.println(s + " is not a palindrome");
}
}
Decimal to Binary -- Example
import java.io.*;
public class DecToBinary {
static StringBuffer toBinary(int decVal) {
StringBuffer sb = new StringBuffer("");
if (decVal == 0)
sb.insert(0,"0"); //note insert position
else
while (decVal != 0) {
if (decVal%2 == 0)
sb.insert(0,"0"); //note insert position
else
sb.insert(0,"1"); //note insert position
decVal = decVal / 2;
}
return sb;
}
Decimal to Binary – Example (cont.)
import java.io.*;
class test1 {
public static void main(String args[])throws Exception {
String s;
int a,b,c;
BufferedReader br= new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter two values");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
c=a+b;
System.out.println("Addition is:" + c);
}}
Reading a character Using Buffered Reader
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');
}
}
Using Scanner class
import java.util.*;
class test3 {
public static void main(String args[])
{
double a, b, c;
System.out.println("Enter The values:");
Scanner sc= new Scanner(System.in);
a=sc.nextDouble();
b=sc.nextDouble();
c=a+b;
System.out.println("The value of addition is :" +c );
}
}
Reading a character
import java.util.Scanner;
public class ScDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a character");
char c = sc.next().charAt(0);
System.out.println("c = "+c);
}
}
Java Garbage Collection
• In java, garbage means unreferenced
objects.
• Garbage Collection is process of reclaiming
the runtime unused memory automatically.
In other words, it is a way to destroy the
unused objects.
• To do so, we were using free() function in C
language and delete() in C++. But, in java
it is performed automatically. So, java
provides better memory management.
Advantage of Garbage Collection
package testgarb;
public class TestGarb {
public void finalize(){
System.out.println("object is garbage collected");
}
void show()
{
System.out.println("method called");
}
public static void main(String args[])
{
TestGarb s1=new TestGarb();
TestGarb s2=new TestGarb();
s1=null;
s2=null;
System.gc();
s1.show();
}
}
• object is garbage collected
• object is garbage collected
finalize() method
• Sometime an object will need to perform some
specific task before it is destroyed such as
closing an open connection or releasing any
resources held. To handle such
situation finalize() method is used.
• finalize() method is called by garbage collection
thread before collecting object. Its the last
chance for any object to perform cleanup utility.
• Signature of finalize() method
• protected void finalize() { //finalize-code }
Some Important Points to Remember
• finalize() method is defined
in java.lang.Object class, therefore
it is available to all the classes.
• finalize() method is declare
as proctected inside Object class.
• finalize() method gets called only
once by GC threads.
Class
b1
Width
Box object
b2 Height
Depth
Assigning Object Reference Variables
• Although b1 and b2 both refer to the same object, they are not
linked in any other way.
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
• Here, b1 has been set to null, but b2 still points to the original
object.
Adding a Method to a class
import java.util.*;
class Box {
class Box {
int width;
int height;
int depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}}
class BoxDemo3 {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
Box mybox1 = new Box();
Box mybox2 = new Box();
System.out.println("Enter the values for first Box:");
mybox1.width = sc.nextInt();
mybox1.height = sc.nextInt();
mybox1.depth = sc.nextInt();
System.out.println("Enter the values for Second Box:");
mybox2.width = sc.nextInt();
mybox2.height = sc.nextInt();
mybox2.depth = sc.nextInt();
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}}
Returning a Value
// Now, volume() returns the volume of a box.
import java.util.*;
class Box {
int width;
int height;
int depth;
double volume() { // compute and return volume
return width * height * depth;
} }
class BoxDemo4 {
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
System.out.println("Enter the values for first Box:");
mybox1.width = sc.nextInt();
mybox1.height = sc.nextInt();
mybox1.depth = sc.nextInt();
System.out.println("Enter the values for Second Box:");
mybox2.width = sc.nextInt();
mybox2.height = sc.nextInt();
mybox2.depth = sc.nextInt();
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume(); // get volume of second box
System.out.println("Volume is " + vol); } }
Adding a Method That Takes Parameters
// This program uses a parameterized method.
import java.util.*;
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}}
class BoxDemo5 {
public static void main (String args[]) {
double a, b, c;
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
Scanner sc= new Scanner(System.in);
System.out.println(“enter three values”);
a= sc.nextDouble();
b= sc.nextDouble();
c= sc.nextDouble();
// initialize each box
mybox1.setDim(a, b, c);
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol); } }
Constructors
• Constructors are required to create objects for a class. Constructors
are used to initialize the instance variables of an object.
• Constructor declaration looks like method declaration. It must have
the same name as that of the class and have no return type.
• Constructors can be classified into two types, default constructors
and parametarized constructors.
• If you don't define a constructor, then the compiler creates a
default constructor. Default constructors do not contain any
parameters. Default constructors are created only if there are no
constructors defined by us.
• Prametarized constructors are required to pass parameters on
creation of objects. We can overload constructors with different
datatypes as its parameters.
• Use 'this()' to communicate from one constructor to another
constructor in the same class.
• Use 'super()' to communicate with super class constructor.
Constructors
/* Here, Box uses a constructor to initialize the dimensions of a box. */
import java.util.*;
class Box {
double width;
double height;
double depth;
Box() { // This is the constructor for Box.
System.out.println("Constructing Box");
Scanner sc=new Scanner(System.in);
System.out.println("Enter weight, height and depth");
width = sc.nextDouble();
height = sc.nextDouble();
depth = sc.nextDouble(); }
double volume() { // compute and return volume
return width * height * depth;
}}
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box(); // declare, allocate, and initialize Box objects
Box mybox2 = new Box();
double vol;
vol = mybox1.volume(); // get volume of first box
System.out.println("Volume is " + vol);
vol = mybox2.volume(); // get volume of second box
System.out.println("Volume is " + vol); } }
Parameterized Constructors
/* Here, Box uses a parameterized constructor to initialize the dimensions of a box. */
import java.util.*;
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}}
class BoxDemo7 {
public static void main(String args[]) {
double a, b, c;
Scanner sc= new Scanner(System.in);
System.out.println(“enter three values”);
a= sc.nextDouble();
b= sc.nextDouble();
c= sc.nextDouble();
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(a, b, c);
System.out.println(“enter another three values”);
a= sc.nextDouble();
b= sc.nextDouble();
c= sc.nextDouble();
Box mybox2 = new Box(a, b, c);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol); } }
Overloading Methods
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
Scanner sc= new Scanner(System.in);
double result, d;
int a,b;
ob.test();
System.out.println(“enter a value”);
a= sc.nextInt();
ob.test(10);
System.out.println(“enter another value”);
b= sc.nextInt();
ob.test(a, b);
System.out.println(“enter a double value”);
d= sc.nextDouble();
result = ob.test(d);
System.out.println("Result of ob.test(d): " + result); } }
Overloading Constructors
/* Here, Box defines three constructors to initialize the dimensions of a box various ways. */
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}}
Cont..
class OverloadCons {
public static void main(String args[]) {
double a,b,c;
System.out.println(“enter three values”);
a= sc.nextDouble();
b= sc.nextDouble();
c= sc.nextDouble();
Box mybox1 = new Box(a, b, c);
Box mybox2 = new Box();
Box mycube = new Box(b);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
call by value
import java.util.*;
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a,b;
Scanner sc= new Scanner(System.in);
System.out.println(“Enter two values”);
a= sc.nextInt();
b= sc.nextInt();
System.out.println("a and b before call: " + a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
}}
– When you pass a simple type to a method, it is passed by value.
– The parameter that receives the argument has no effect outside the
method.
call by reference
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j; }
void meth(Test o) { // pass an object
o.a *= 2;
o.b /= 2; }}
class CallByRef {
public static void main(String args[]) {
int a,b;
Scanner sc= new Scanner(System.in);
System.out.println(“Enter two values”);
a= sc.nextInt();
b= sc.nextInt();
Test ob = new Test(a, b);
System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); }}
Returning Objects
A method can return any type of data, including class types that you create.
class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}}
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: “ + ob2.a);
}
}
Copy Constructor
• A copy constructor is a constructor that replicates or duplicates an existing
object.
• So it is called copy constructor.
• It takes parameter is a reference to an object of the same class to which
the constructor is depend.
E.g.: A a= new A();
A b= new A(a);
Create a new object ‘b’ that is a duplicate of the object ‘a’ passed to it.
class Copy{
int a, b;
public Copy(int a1, int b1){
a=a1;
b=b1; }
public Copy(Copy c) // Copy constructor
{
a=c.a;
b=c.b; }
void view() {
System.out.println("a=" +a+ "b=" +b);
} }
Copy Constructor
class CopyTest{
public static void main(String args[]) {
Copy test = new Copy(10, 15);
System.out.println("first constructor");
test.view();
Copy test1 = new Copy(test); //invoke copy constructor
System.out.println("Second constructor");
test1.view(); } }
Static keyword
• The static keyword is used in java mainly for memory
management.
• It is used with variables, methods, blocks and nested class.
• It is a keyword that are used for share the same variable or method
of a given class.
• This is used for a constant variable or a method that is the same for
every instance of a class.
• The main method of a class is generally labeled static.
• No object needs to be created to use static variable or call static
methods, just put the class name before the static variable or
method to use them.
• Static method can not call non-static method.
• Static can not refer to super.
Use of Static
• Static variable
• If any variable we declared as static is known as static variable.
• Static variable is used for fulfill the common requirement. For
Example company name of employees,college name of students
etc. Name of the college is common for all students.
• The static variable allocate memory only once in class area at the
time of class loading.
• E.g.: static int i;
• Java static methods:
• Static methods are also similar to static variables, you can access
them with reference to class name, without creating object.
• Inside static methods, you cannot access instance variables or
instance methods. You can only access static variables or static
methods.
• Example of class method:
public static int abs(int a)
Use of Static
import java.util.Scanner;
class Static {
static int a=5;
static int b;
static void math(int c)
{
System.out.println("\nValue of A = " +a);
System.out.println("Value of B = " +b);
System.out.println("Value of C = " +c);
}
static
{
b=a*4;
}
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int a;
System.out.print("\nEnter a value to perform the given task : " );
a=s.nextInt();
math(a); } }
import java.util.*;
class Static1{
static int rollno;
static String name;
static String college ="IINTM";
Static1(int r,String n){
rollno = r;
name = n; }
static void display (){
System.out.println(rollno+" "+name+" "+college); }
public static void main(String args[]){
int roll;
String name;
Scanner sc= new Scanner(System.in);
System.out.println("Enter Name");
name=sc.nextLine();
System.out.println("Enter roll No:");
roll=sc.nextInt();
Static1 s1 = new Static1(roll,name);
display(); }
static {
System.out.println("Static block will execute first");
} }
Command-Line Arguments
• When you want to pass information into a program when you
run it.
• This is done 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.
• Command-line arguments are stored as strings in the String
array passed to main( ).
• Compile this program with class name. java like as normal
program.
• Execute this program by java class name and command-line
arguments.
Command-Line Arguments
class test {
public static void main(String args[])
{
System.out.println("you entered" + args.length + "arguments.");
System.out.println(" First Name:\t" + args[0]);
System.out.println(" Middle Name:\t" + args[1]);
System.out.println( "Last Name:\t" + args[2]);
} }
Second Example----------------------------------------------
class CommandLine {
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}}
This keyword
• The keyword this is useful when you need to refer to instance of the
class from its method.
• The keyword helps us to avoid name conflicts. As we can see in the
program that we have declare the name of instance variable and
local variables same.
• Now to avoid the confliction between them we use this keyword.
Keyword this can be used inside any method to refer to the current
object and it always a reference to the object on which the method
was invoked.
• In the example, this.length and this.breadth refers to the instance
variable length and breadth while length and breadth refers to the
arguments passed in the method.
• We have made a program over this. After going through it you can
better understand.
class Rectangle{
int length, breadth;
void show(int length, int breadth){
this.length=length;
this.breadth=breadth;
}
int calculate(){
return(length*breadth);
}
}
public class UseOfThisOperator{
public static void main(String[] args){
Rectangle rectangle=new Rectangle();
rectangle.show(5,6);
int area = rectangle.calculate();
System.out.println("The area of a Rectangle is : " + area);
}
}
Inheritance
{
//code
}
class B extends A B
{
//code
}
Inheritance
// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
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();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Calling of constructor
• Super class default constructor is implicitly invoked when we create the
child class object.
class x {
x()
{
System.out.println("inside super class default constructor");
}
x(int i)
{
System.out.println("inside super class parameterized constructor");
}}
class y extends x {
}
class inheritance {
public static void main(String args[])
{
y ii= new y();
}}
If the super class parameterized constructor is defined and default
constructor is not defined then compile time error arise.
If the child class parameterized constructor is called the
parent class default constructor is also called at that time.
class x
{
x()
{
System.out.println("inside super class default constructor");
}
x(int i)
{
System.out.println("inside super class parameterized constructor");
}}
class y extends x
{
y(int i) {
System.out.println("inside child class parameterized constructor");
} }
class inheritance1 {
public static void main(String args[])
{
y ii= new y(6);
}}
If the super class default constructor is not defined then inside child
class constructor call the parent class parameterized constructor.
class x
{
x(int i)
{
System.out.println("inside super class parameterized constructor");
}}
class y extends x
{
y(int i) {
super(8);
System.out.println("inside child class parameterized constructor");
} }
class inheritance1 {
public static void main(String args[])
{
y ii= new y(6);
}}
import java.util.*;
class A {
int i, j;
A(int a, int b) {
i=a;
j=b; }
void showij() {
System.out.println("i and j: " + i + " " + j);
} }
class B extends A {
int k;
B(int a, int b, int c) {
super(a,b);
k=c; }
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[]) {
int a,b,c;
Scanner sc=new Scanner(System.in);
System.out.println("enter two values");
a=sc.nextInt();
b=sc.nextInt();
A superOb = new A(a,b);
System.out.println("enter three value");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
B subOb = new B(a,b,c);
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
} }
Multilevel Inheritance:
class A
{
//code
} A
class B extends A
{
//code
}
class C extends B B
{
//code
}
C
Multi-level inheritance
class x {
void show()
{
System.out.println("Hello Java.");
}}
class y extends x {
}
class z extends y
{
z()
{
super.show();
}
}
public class Demoinheritance extends z
{
public static void main(String args[])
{
z obj = new z();
}
}
Multiple Inheritance:
• Not supported by Java.
• Diamond Problem…But supported by C++ To
Overcome this problem we have the concept of Interface..
C D
A
Hierarchical Inheritance:
class A
{
//code
}
class B extends A
{
//code A
}
class C extends A
{
//code
}
class D extends A C B D
{
//code
}
class A {
void DisplayA() {
System.out.println("I am in A"); } }
class B extends A {
void DisplayB() {
System.out.println("I am in B"); } }
class C extends A {
void DisplayC() {
System.out.println("I am in C"); } }
public class MainClass {
public static void main(String args[]) {
System.out.println("Calling for subclass C");
C c = new C();
c.DisplayA();
c.DisplayC();
System.out.println("Calling for subclass B");
B b = new B();
b.DisplayA();
b.DisplayB();
}}
Super
• Whenever a subclass needs to refer to its immediate superclass, it can
do so by use of the keyword super.
• super has two general forms.
• The first calls the superclass’ constructor.
• The second is used to access a member of the superclass that has been
hidden by a member of a subclass.
• If the super class instance variable name is the same as that of the
child class or sub-class instance variable name, then super keyword is
used inside the sub-class to access the super class instance variable.
class x{
int i=9; }
class y extends x {
int i=90;
void showsuper() {
System.out.println(i);
System.out.println(super.i);
} }
class super1 {
public static void main(String args[]) {
y a =new y();
a.showsuper();
} }
Method Overriding
When a method in a subclass has the same name and type
signature as a method in its super class, then the method in the
subclass is said to override the method in the super class.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}}
Cont…
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
Dynamic Method Dispatch
• Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time,
rather than compile time.
• Superclass reference variable can refer to a subclass
object. Java uses this fact to resolve calls to overridden
methods at run time.
• When an overridden method is called through a
superclass reference, Java determines which version of
that method to execute based upon the type of the
object being referred to at the time the call occurs.
• Overridden methods are another way that Java
implements the “one interface, multiple methods” aspect
of polymorphism.
• This determination is made at run time. When different
types of objects are referred to, different versions of an
overridden method will be called.
Dynamic Method Dispatch
// Using run-time polymorphism.
class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
double area() {
System.out.println("Area for Figure is undefined.");
return 0;
}}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}}
class FindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}}
final
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}}
final to Prevent Inheritance
interface A{
void display();
}
interface B extends A{
void show();
}
class C implements B{
public void display(){
System.out.println("interface A");
}
public void show(){
System.out.println("Interface B");
}
}
class D
{
public static void main(String arr[])
{
C c=new C();
c.display();
c.show();
}}
import java.util.*;
interface IntStack {
void push(int item);
int pop(); }
class FixedStack implements IntStack {
private int stck[];
private int tos;
FixedStack(int size) {
stck = new int[size];
tos = -1; }
public void push(int item) {
if(tos==stck.length-1)
System.out.println("Stack is full.");
else
stck[++tos] = item; }
public int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0; }
else
return stck[tos--]; } }
class IFTest {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int size1, size2;
System.out.println("Enter the size of stack1 and stack2");
size1=sc.nextInt();
size2=sc.nextInt();
FixedStack mystack1 = new FixedStack(size1);
FixedStack mystack2 = new FixedStack(size2);
int a;
System.out.println("Enter elements of stack");
for(int i=0; i<size1; i++) {
a=sc.nextInt();
mystack1.push(a); }
System.out.println("Enter elements of Second stack");
for(int i=0; i<size2; i++) {
a=sc.nextInt();
mystack2.push(a); }
System.out.println("Stack in mystack1:");
for(int i=0; i<size1; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<size2; i++)
System.out.println(mystack2.pop());
}}
Interface
• An interface is not a substitute for multiple inheritance.
• The difference is that the interface approach only
enables you only inherit method descriptions not
implementations.
• If a class implements multiple interface that class must
provide all of the functionality for the methods defined
in the interface.
• Interface are used to define standard behavior that can
be implemented by any class any where in the class
hierarchy.
Example to implement multiple inheritance
import java.util.*;
import java.io.*;
interface Exam {
void percent_cal(); }
class Student {
String name;
int roll_no,mark1,mark2;
Student(String n, int r, int m1, int m2) {
name=n;
roll_no=r;
mark1=m1;
mark2=m2; }
void display() {
System.out.println ("Name of Student: "+name);
System.out.println ("Roll No. of Student: "+roll_no);
System.out.println ("Marks of Subject 1: "+mark1);
System.out.println ("Marks of Subject 2: "+mark2); }
}
class Result extends Student implements Exam {
Result(String n, int r, int m1, int m2) {
super(n,r,m1,m2);
}
public void percent_cal() {
int total=(mark1+mark2);
float percent=total*100/200;
System.out.println ("Percentage: "+percent+"%");
}
void display()
{
super.display();
}
}
public class Multipleq
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println ("Enter Name of Student");
String name=sc.nextLine();
System.out.println ("Enter RollNo of Student");
int rollno= sc.nextInt();
System.out.println ("Enter Marks of Subject1");
int marks1=sc.nextInt();
System.out.println ("Enter Marks of Subject2");
int marks2=sc.nextInt();
Result R = new Result(name,rollno,marks1,marks2);
R.display();
R.percent_cal();
}
}
Nested Interface
• An interface which is declared inside another interface or class is called
nested interface.
• They are also known as inner interface.
• Since nested interface cannot be accessed directly, the main purpose of
using them is to resolve the namespace by grouping related interfaces (or
related interface and class) together.
• This way, we can only call the nested interface by using outer class or outer
interface name followed by dot( . ), followed by the interface name.
interface MyInterfaceA
{
void display();
interface MyInterfaceB{
void myMethod(); } }
class NestedInterfaceDemo1 implements MyInterfaceA.MyInterfaceB
{
public void myMethod()
{
System.out.println("Nested interface method"); }
public static void main(String args[])
{
MyInterfaceA.MyInterfaceB obj= new NestedInterfaceDemo1();
obj.myMethod();
}
}
Difference Between Abstract class and Interface
Packages Introduction
• The main feature of OOP is its ability to support
the reuse of code:
– Extending the classes (via inheritance)
– Extending interfaces
• The features in basic form limited to reusing
the classes within a program.
• What if we need to use classes from other
programs without physically copying them into
the program under development ?
• In Java, this is achieved by using what is
known as “packages”, a concept similar to
“class libraries” in other languages.
143
Packages
• A java package is a group of similar types of
classes, interfaces and sub-packages.
• Package in java can be categorized in two form,
built-in package and user-defined package.
• The benefits of organising classes into packages
are:
– The classes contained in the packages of other
programs/applications can be
reused.
– In packages classes can be unique compared with
classes in other packages. That two classes in two
different packages can have the same name. If there
is a naming clash, then classes can be accessed with
their fully qualified name.
– Classes in packages can be hidden if we don’t want
other packages to access them.
– Packages also provide a way for separating “design”
144
from coding.
Java Foundation Packages
• Java provides a large number of classes groped into
different packages based on their functionality.
• The six foundation Java packages are:
– java.lang
• Contains classes for primitive types, strings, math functions,
threads, and exception
– java.util
• Contains classes such as vectors, hash tables, date etc.
– java.io
• Stream classes for I/O
– java.awt
• Classes for implementing GUI – windows, buttons, menus etc.
– java.net
• Classes for networking
– java.applet
• Classes for creating and implementing applets
145
Using System Packages
• The packages are organised in a hierarchical structure.
For example, a package named “java” contains the
package “awt”, which in turn contains various classes
required for implementing GUI (graphical user interface).
java
lang “java” Package containing
“lang”, “awt”,.. packages;
String Can also contain classes.
awt
Graphics awt Package containing
Font classes
Classes containing
Image
methods
146 …
Advantages of using a package in Java
• These are the reasons why you should use packages in Java:
• Reusability: While developing a project in java, we often feel
that there are few things that we are writing again and again in
our code. Using packages, you can create such things in form
of classes inside a package and whenever you need to perform
that same task, just import that package and use the class.
• Better Organization: Again, in large java projects where we
have several hundreds of classes, it is always required to group
the similar types of classes in a meaningful package name so
that you can organize your project better and when you need
something you can quickly locate it and use it, which improves
the efficiency.
• Name Conflicts: We can define two classes with the same
name in different packages so to avoid name collision, we can
use packages.
Creating Packages
• Java supports a keyword called “package” for creating
user-defined packages. The package statement must
be the first statement in a Java source file (except
comments and white spaces) followed by one or more
classes.
package myPackage;
public class ClassA {
// class body
}
class ClassB {
// class body
}
• Package name is “myPackage” and classes are
considered as part of this package; The code is saved
in a file called “ClassA.java” and located in a directory
148 called “myPackage”.
Creating Sub Packages
• Classes in one or more source files can be part of the same
packages.
• As packages in Java are organised hierarchically, sub-
packages can be created as follows:
– package myPackage.Math
– package myPackage.secondPakage.thirdPackage
• Store “thirdPackage” in a subdirectory named “myPackage\
secondPackage”. Store “secondPackage” and “Math” class in a
subdirectory “myPackage”.
149
Accessing a Package
• As indicated earlier, classes in packages can be
accessed using a fully qualified name or using a
short-cut as long as we import a corresponding
package.
• The general form of importing package is:
– import package1[.package2][…].classname
– Example:
• import myPackage.ClassA;
• import myPackage.secondPackage
– All classes/packages from higher-level package can
be imported as follows:
• import myPackage.*;
150
Protection and Packages
• All classes (or interfaces) accessible to all others
in the same package.
• Class declared public in one package is
accessible within another. Non-public class is not
• Members of a class are accessible from a
difference class, as long as they are not private
• protected members of a class in a package are
accessible to subclasses in a different class
151
Visibility - Revisited
• Public keyword applied to a class, makes it
available/visible everywhere. Applied to a
method or variable, completely visible.
• Private fields or methods for a class only visible
within that class. Private members are not visible
within subclasses, and are not inherited.
• Protected members of a class are visible within
the class, subclasses and also within all classes
that are in the same package as that class.
152
Visibility Modifiers
Accessible to: public protected Package private
(default)
Same Class Ye s Ye s Ye s Ye s
Class in package Ye s Ye s Ye s No
Subclass in Ye s Ye s No No
different package
Non-subclass Ye s No No No
different package
153
Adding a Class to a Package
• Consider an existing package that contains a
class called “Teacher”:
package pack1;
public class Teacher
{
// class body
}
156
Extending a Class from Package
157
Package Example
package emppack;
public class Company {
String compname, address;
public Company(String c, String a)
{
compname=c;
address=a;
}
public void display()
{
System.out.println("Company Details");
System.out.println("Company Name:"+ compname);
System.out.println("Company Address:"+ address);
}}
158
Package Example
package emppack;
public class Employee
{
int empid;
String empname, empaddr;
public Employee(int i, String n, String a){
empid=i;
empname=n;
empaddr=a;
}
public void displayinfo()
{
System.out.println("Employee Details");
System.out.println("Employee ID:"+empid);
System.out.println("Employee Name:"+empname);
System.out.println("Employee Address"+empaddr);
}
} 159
import emppack.Employee;
import emppack.Company;
import java.util.*;
class PackageDemo {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter company name");
String cname=sc.nextLine();
System.out.println("Enter company Address");
String caddr=sc.nextLine();
System.out.println("Enter Employee name");
String ename=sc.nextLine();
System.out.println("Enter Employee Address");
String eaddr=sc.nextLine();
System.out.println("Enter EmployeeId");
int eid=sc.nextInt();
Company c= new Company(cname,caddr);
Employee e=new Employee(eid,ename, eaddr);
c.display();
e.displayinfo(); } }
160
Summary