By: Abhishek Khare · PDF file© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights...
Transcript of By: Abhishek Khare · PDF file© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights...
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
MCA – 405 Elective –I (A) Java Programming & Technology
By: Abhishek Khare (SVIM - INDORE M.P)
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
UNIT-I The Java Environment, Basics, Object
Oriented Programming in Java, Inheritance
The Java Environment: History of Java: Comparison of Java and C++
Java as an object oriented language: Java buzzwords
A simple program, its compilation and execution; the concept of CLASSPATH
Basic idea of application and applet
Basics: Data types; Operators- precedence and associativity; Type conversion
The decision making – if, if..else, switch; loops – for, while, do…while
special statements–return, break, continue, labeled break, labeled continue
Modular programming methods;
arrays; memory allocation and garbage collection in java keywords.
Object Oriented Programming in Java: Class; Packages; scope and lifetime;
Access specifies
Constructors; Copy constructor; this pointer
finalize () method
Inheritance : Inheritance basics,
method overriding, dynamics method dispatch, abstract classes. 2
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Java started out as a research project Research began in 1991 as the Green Project Project was chartered to anticipate and plan for next wave of computing “Green Team” determined consumer devices and computers would converge Team focused on TV set-top boxes and interactive TV industries
Research efforts birthed a new language, OAK Created by James Gosling - “the father of Java” Language was created with 5 main goals:
1. It should be object oriented 2. A single representation of a program could be executed on multiple operating systems 3. It should fully support network programming 4. It should execute code from remote sources securely 5. It should be easy to use
Oak was renamed Java in 1994
3
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved. 4
Java as an object oriented language: Java buzzwords
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Simple and Powerful Object Oriented Portable Architecture Neutral Distributed Multi-threaded Robust, Secure/Safe Interpreted High Performance Dynamic programming language/platform.
5
How to compile and run java programs?
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Write Once, Run Anywhere
6
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Download and Install JDK (Java Development Kit)
Download the latest version of jdk from http://java.sun.com/javase/downloads/index.jsp. Once you download the exe file you can now install it.
Double Click the icon of downloaded exe.
7
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
The concept of PATH, CLASSPATH, JAVA_HOME
In PATH Environment variable you need to specify only .exe (Executable files that Operating System Uses).
In CLASSPATH environment you need to specify only .class files i.e. you are helping Java Virtual Machine (JVM) to find Java class files
Note: For running java application you need to set PATH alone. For versions above jdk 1.5, JAVA_HOME itself is enough. No need to set CLASSPATH.
Variable name: JAVA_HOME
Variable value: C:\Program Files\Java\jdk1.6.0_11
Variable name: PATH
Variable value: %PATH%;%JAVA_HOME%\bin
8
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
What is the meaning of PATH and CLASSPATH ? How it is set in environment variable?
PATH variable on command prompt C:\>set path=%path;C:\Java\jdk1.6.0_03\bin%
CLASSPATH variable on command prompt C:\>set classpath=%classpath;C:\Java\jdk1.6.0_03\lib%
9
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved. 10
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
An overview of the software development process.
1. All source code is first written in plain text files ending with the .java extension 2. Those source files are then compiled into .class files by the javac compiler. 3. A .class file does not contain code that is native to your processor; it instead contains
bytecodes. 4. Bytecodes are the machine language of the Java Virtual Machine (JVM). 5. The java launcher tool then runs your application with an instance of the Java Virtual
Machine.
11
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
How to run java program? Step 1 – Coding Create a text file Hello.java and copy below contents. public class FirstHello { public static void main(String[] args) { System.out.println("Hello Java"); } }
Step 2 - Deployment 1. Create a folder 'c:\javaprograms'. 2. Create or copy Hello.java into 'c:\javaprograms' folder. 3. Open your command prompt and go to 'c:\javaprograms'
4. Compile Hello.java with help of javac Hello.java
command. Command will create class file in the same folder.
Congratulations!! your First Java program is ready to serve.
12
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Step 3 - Testing 1. Make sure you are on Command Prompt under c:\javaprograms
directory
2. Now start your First java program from command prompt with help of java Hello command.
Output It will show a message. Hello java...
Error : C:\javaprograms>javac FirstHello.java 'javac' is not recognized as an internal or external command, operable program or batch file. Resolution : Check your PATH environment variable. JAVA_HOME is not in PATH. Set path by SET PATH=%JAVA_HOME%/bin;%PATH%
13
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Basic idea of application and applet
We can develop two types of Java Programs: 1. Java Application 2. Web Applets
Applets are the small programs while applications are larger
programs.
Applets don't have the main method while in an application execution
starts with the main method.
Applets can run in our browser's window or in an appletviewer while
applications run on command prompt.
Applets are designed just for handling the client site problems. while
the java applications are designed to work with the client as well as
server.
14
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Basics: Data types; Operators- precedence and associativity; Type conversion
There are two data types available in Java: 1. Primitive Data Types 2. Reference/Object Data Types
Primitive Data Types:
There are eight primitive data types supported by Java.
1. byte: 1. Byte data type is a 8-bit signed integer. 2. Minimum value is -128 (-2^7) 3. Maximum value is 127 (inclusive)(2^7 -1) 4. Default value is 0 5. Byte data type is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an int. Example : byte a = 100 , byte b = -50
15
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
2. short: 1. Short data type is a 16-bit signed integer. 2. Minimum value is -32,768 (-2^15) 3. Maximum value is 32,767(inclusive) (2^15 -1) 4. Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an int 5. Default value is 0. Example : short s= 10000 , short r = -20000
3. int: 1. Int data type is a 32-bit signed integer. 2. Minimum value is - 2,147,483,648.(-2^31) 3. Maximum value is 2,147,483,647(inclusive).(2^31 -1) 4. Int is generally used as the default data type for integral values unless there is a concern
about memory. 5. The default value is 0. Example : int a = 100000, int b = -200000
4. long: 1. Long data type is a 64-bit signed integer. 2. Minimum value is -9,223,372,036,854,775,808.(-2^63) 3. Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1) 4. This type is used when a wider range than int is needed. 5. Default value is 0L. Example : int a = 100000L, int b = -200000L
16
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
5. float: 1. Float data type is a single-precision 32-bit IEEE 754 floating point. 2. Float is mainly used to save memory in large arrays of floating point numbers. 3. Default value is 0.0f. 4. Float data type is never used for precise values such as currency. Example : float f1 = 234.5f
6. double: 1. double data type is a double-precision 64-bit IEEE 754 floating point. 2. This data type is generally used as the default data type for decimal values. generally
the default choice. 3. Double data type should never be used for precise values such as currency. 4. Default value is 0.0d. Example : double d1 = 123.4
7. boolean: 1. boolean data type represents one bit of information. 2. There are only two possible values : true and false. 3. This data type is used for simple flags that track true/false conditions. 4. Default value is false. Example : boolean one = true
8. char: 1. char data type is a single 16-bit Unicode character. 2. Minimum value is '\u0000' (or 0). 3. Maximum value is '\uffff' (or 65,535 inclusive). 4. Char data type is used to store any character. Example . char letterA ='A'
17
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Reference Data Types:
Reference variables are created using defined constructors of the classes.
They are used to access objects.
These variables are declared to be of a specific type that cannot be changed. For
example, Employee, Credit_card etc.
Class objects, and various type of array variables come under reference data
type.
Default value of any reference variable is null.
A reference variable can be used to refer to any object of the declared type or
any compatible type.
Example : Animal animal = new Animal("giraffe");
18
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
There are three kinds of variables in Java: 1. Local variables 2. Instance variables 3. Class/static variables
variables in Java
Local variables : 1. Local variables are declared in methods, constructors, or blocks.
2. Local variables are created when the method, constructor or block is entered
and the variable will be destroyed once it exits the method, constructor or block.
3. Access modifiers cannot be used for local variables.
4. Local variables are visible only within the declared method, constructor or block.
5. Local variables are implemented at stack level internally.
6. There is no default value for local variables so local variables should be declared
and an initial value should be assigned before the first use.
19
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Instance variables : 1. Instance variables are declared in a class, but outside a method, constructor
or any block. 2. When a space is allocated for an object in the heap a slot for each instance
variable value is created. 3. Instance variables are created when an object is created with the use of the
key word 'new' and destroyed when the object is destroyed.
The difference between instance and local variables
20
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Class/static variables : 1. Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block. 2. There would only be one copy of each class variable per class, regardless of
how many objects are created from it.
21
© 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
class Circle1 { static int num_circles = 0; // class variable: how many circles created public double x, y, r; // instance vars: the center and the radius public Circle1(double x, double y, double r) { this.x = x; this.y = y; this.r = r; num_circles++; } public Circle1(double r) { this(0.0, 0.0, r); } public Circle1(Circle1 c) { this(c.x, c.y, c.r); } public Circle1() { this(0.0, 0.0, 1.0); } public double circumference() { return 2 * 3.14159 * r; } public double area() { return 3.14159 * r*r; } } public class Circle { public static void main(String[] args) { Circle1 C1=new Circle1(2); Circle1 C2=new Circle1(C1); Circle1 C3=new Circle1(); System.out.println("Number of circles created: " + Circle1.num_circles); System.out.println("Number of circles created: " + C1.area()); System.out.println("Number of circles created: " + C1.circumference()); } }
22
23 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
24 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
What are Methods?
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name. Think of a method as a subprogram that acts on data and often returns a value.
There are two basic types of methods:
Built-in: Build-in methods are part of the compiler package, such as System.out.println( ) and System.exit(0).
User-defined: User-defined methods are created by you, the programmer. These methods take-on names that you assign to them and perform tasks that you create.
25 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
// 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; } } public class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.2); System.out.println("Result of ob.test(123.2): " + result); } }
Method
overloading
arrays; memory allocation and garbage collection in java keywords
26 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
The java array enables the user to store the values of the same type in contiguous memory allocations. Arrays are always a fixed length abstracted data structure which can not be altered when required.
public class Sum { public static void main(String[] args) { int[] x = new int [101]; for (int i = 0; i<x.length; i++ ) x[i] = i; int sum = 0; for(int i = 0; i<x.length; i++) sum += x[i]; System.out.println(sum); }
}
27 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Multi-dimensional arrays
Syntax: int[ ][ ] nums = new int[5][4]
A 2-D Array is really an Array of Arrays
The above is really equivalent to a 3-step process:
// create the single reference nums (yellow square)
int [][] nums;
// create the array of references (blue squares) nums
= new int[5][];
// this create the second level of arrays (red squares) for (int i=0; i < 5 ; i++) nums[i] = new int[4]; // create arrays of integers
28 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
public class twoD { public static void main(String [] args) { int [][] a={{1},{2,3},{4,5,6},{7,8,9,10}}; for(int i=0;i<a.length;i++) { for(int j=0;j<a[i].length;j++) { System.out.print(" "+a[i][j]); } System.out.println("\tLength of"+i+"row is :"+a[i].length); System.out.println(); } } }
Garbage Collection in Java
1) objects are created on heap in Java irrespective of there scope e.g. local or member variable. while its worth noting that class variables or static members are created in method area of Java memory space and both heap and method area is shared between different thread.
2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
3) Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
4) Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
5) You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
6) There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
7) 8) If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space
29 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Understanding of main function of java
30 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
class two { static int i; static int geti() { return i; } } public class twoDD { static int j;
public static void main(String [] args) { two t=new two(); System.out.println("value is:"+t.geti()+j); } }
Command Line Argument
class Demo
{
public static void main(String [ ] args)
{
System.out.println("Argument one = "+args[0]);
System.out.println("Argument two = "+args[1]);
}
}
31 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
args.length
Packages
32 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier etc.
A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations ) providing access protection and name space management.
Some of the existing packages in Java are::
java.lang - bundles the fundamental classes
java.io - classes for input , output functions are bundled in this package
Creating a package:
33 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
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. If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an unnamed package.
package p1; class c1{ public void m1() { System.out.println("Method m1 of Class c1"); } public static void main(String args[]){ c1 obj = new c1(); obj.m1(); } }
Step 1) Save the file as Demo.java. Compile the file as, javac – d . Demo.java Step 2) Run the code as java p1.c1
How to use packages set CLASSPATH=.;C:\;
34 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Importing a package
To create an object of a class (bundled in a package), in your code, you have to use its fully qualified name.
// Using packages created in earlier assignment
package p3;
import p1.*; //imports classes of package p1
class c3{
public void m3(){ System.out.println("Method m3 of Class c3");
}
public static void main(String args[]){
c1 obj1 = new c1(); obj1.m1();
c3 obj2 = new c3(); obj2.m3();
}
}
35 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
package p1; public class c1 { public void m1() { System.out.println("Method m1 of class c1"); } }
Access Modifiers/ Specifier
36 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
1. public 2. private 3. protected 4. default
Default: 1. Default access modifier is no-modifier. i.e. when you do not specify any
access modifier explicitly for a method, a variable or a class 2. Default access also means “package-level” access. 3. That means a default member can be accessed only inside the same package
in which the member is declared.
Protected: 1. Protected access modifier is the a little tricky and you can say is a superset
of the default access modifier. 2. Protected members are same as the default members as far as the access
in the same package is concerned. 3. protected members are “accessible outside the package only through
inheritance“.
37 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Access Modifier -> Access Location
default(None) protected public private
Same class YES YES YES YES
Subclass in same package
YES YES YES NO
Other class in same package
YES YES YES NO
Subclass in other packages
NO YES YES NO
Non-subclasses in other packages
NO NO YES NO
Constructors; Copy constructor; this pointer
Constructor is a special method in java. The purpose of the constructor is to assign initial values to the instance variable of the class.
Constructor is always called by new operator. Constructors are declared just like as we declare methods, except that the constructors don’t have any return type.
Since constructors are called by JVM at runtime during object instantiation so it does not required any return value.
Default constructor does not require any parameter. It is called default constructor only because it does not receive any parameter. If the parameters are passed in the constructor then it will no longer be a default constructor
38 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
The this Keyword
39 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Sometimes a method will need to refer to the object that invoked it.
To allow this, Java defines the this keyword.
this can be used inside any method to refer to the current object.
this is always a reference to the object on which the method was invoked.
public Circle1(double x, double y, double r) { this.x = x; this.y = y; this.r = r; }
Constructor Overloading
40 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
class Circle1 { static int num_circles = 0; // class variable: how many circles created public double x, y, r; // instance vars: the center and the radius
public Circle1(double x, double y, double r) { this.x = x; this.y = y; this.r = r; num_circles++; } public Circle1(double r) { this(0.0, 0.0, r); } public Circle1(Circle1 c) { this(c.x, c.y, c.r); } public Circle1() { this(0.0, 0.0, 1.0); } public double circumference() { return 2 * 3.14159 * r; } public double area() { return 3.14159 * r*r; } }
The finalize( ) Method
41 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Sometimes an object will need to perform some action when it is destroyed. Example: If an object is holding some non-Java resource such as a file handle. Java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector.
The finalize( ) method has this general form: protected void finalize( ) { // finalization code here }
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class.
Inheritance in Java
42 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Inheritance is a compile-time mechanism in Java that allows you to extend a class (called the base class or superclass) with another class (called the derived class or subclass). 1. class inheritance – create a new class as an extension of another class, primarily for
the purpose of code reuse. That is, the derived class inherits the public methods and public data of the base class. Java only allows a class to have one immediate base class, i.e., single class inheritance. 2. interface inheritance – create a new class to implement the methods defined as part of
an interface for the purpose of subtyping. Java supports multiple interface inheritance.
43 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Example of class inhertiance package MyPackage; class Base { private int x; public int f() { ... } protected int g() { ... } } class Derived extends Base { private int y; } public void h() { y = g(); ... } }
Super Keyword
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.
• super( ) must always be the first statement executed inside a subclass’
constructor.
44 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
A subclass can call a constructor defined by its superclass by use of the following form of super: super(arg-list);
class BoxWeight extends Box { double weight; // weight of box // initialize width, height, and depth using super() BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } }
A Second Use for super
45 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form: super.member Here, member can be either a method or an instance variable.
What is the difference between super keyword and this keyword ?
This second form of super is most applicable to situations in which member names of a subclass hide
members by the same name in the superclass.
Abstract Base Classes
46 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
abstract public class abstract-base-class-name { // abstract class has at least one abstract method public abstract return-type abstract-method-name ( formal-params ); ... // other abstract methods, object methods, class methods } public class derived-class-name extends abstract-base-class-name { public return-type abstract-method-name (formal-params) { stmt-list; } ... // other method implementations } It would be an error to try to instantiate an object of an abstract type: abstract-class-name obj = new abstract-class-name(); // ERROR! That is, operator new is invalid when applied to an abstract class.
“An abstract class is a class that leaves one or more method implementations unspecified by declaring one or more methods abstract. An abstract method has no body (i.e., no implementation). A subclass is required to override the abstract method and provide an implementation. Hence, an abstract class is incomplete and cannot be instantiated, but can be used as a base class.
Interfaces
47 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
An abstract class mixes the idea of mutable data in the form of instance
variables, non-abstract methods, and abstract methods.
An abstract class with only static final instance variables and all
abstract methods is called an interface.
The class that implements the interface provides an implementation for
each method, just as with an abstract method in an abstract class.
All methods declared in an interface are implicitly abstract and implicitly
public
You can define data in an interface, but it is less common to do so. If
there are data fields defined in an interface, then they are implicitly defined
to be:
public, static, and final
48 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Interface declaration Interface names and class names in the same package must be distinct. public interface interface-name { // if any data are defined, they must be constants public static final type-name var-name = constant-expr; // one or more implicitly abstract and public methods return-type method-name ( formal-params ); }
Note that a class and an interface in the same package cannot share the same name.
Method Overriding In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.
When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden.
49 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
// Method overriding. 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); } } 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 } } The output produced by this program is shown here: k: 3
If you wish to access the superclass version of an overridden method, you can do so by using super.
void show() { super.show(); // this calls A's show() System.out.println("k: " + k); }
Here, super.show( ) calls the superclass version of
show( ).
Dynamic Method Dispatch
50 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism.
Important principle: a superclass reference variable can refer to a subclass object.
51 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.
// Dynamic Method Dispatch class A { void callme() { System.out.println("Inside A's callme method"); } } class B extends A { // override callme() void callme() { System.out.println("Inside B's callme method"); } } class C extends A { // override callme() void callme() { System.out.println("Inside C's callme method"); } } class Dispatch { public static void main(String args[]) { A a = new A(); // object of type A B b = new B(); // object of type B C c = new C(); // object of type C A r; // obtain a reference of type A r = a; // r refers to an A object r.callme(); // calls A's version of callme r = b; // r refers to a B object r.callme(); // calls B's version of callme r = c; // r refers to a C object r.callme(); // calls C's version of callme } }
The output from the program is shown here: Inside A’s callme method Inside B’s callme method Inside C’s callme method
52 © 2013 Abhishek Khare JAVA Notes (SVIM) All Rights Reserved.