what is java? java is a new programming language from sun microsystems. (mid-1995)
DESCRIPTION
Features of Java: Strongly Typed Compiled & Interpreted OO Programming GUI (AWT, Swings) Database Access (JDBC) Network Support (Sockets) Built in Security Run on all computers by layering Lib. on top of any OS - PowerPoint PPT PresentationTRANSCRIPT
What is Java?Java is a new programming language from Sun Microsystems. (mid-1995)
Features of Java:• Strongly Typed• Compiled & Interpreted• OO Programming• GUI (AWT, Swings)• Database Access (JDBC)• Network Support (Sockets) • Built in Security• Run on all computers by layering
Lib. on top of any OS• Java provides Framework for RE-
USABLE components JavaBeans, thin clint/Server JavaRMI, TCP/IP Sockets, Secure browser based software Java Applets.
• Multi-threading code• GC
• Java has large set of rich libraries.
These lib are Building blocks for your systems.Lib are Identical on all java implementations on different computers
• Robust Language DesignSome common bugs either can’t happen or are caught as soon as they occur.
• E.g. Array Index bounds,Strongly typedType conversions are checked for validity at run time.The Memory Address Arithmetica common bug in C is not allowed
Oracle to take over Sun Microsystems, in a deal worth €5.17 billion ($7.75 billion)
//Rolls colored text across the screenimport java.awt.*;Class myframe extends Frame{
static int x=0, y=120; //x,y positions to display messagestatic int i=0;static int LtoR=1;Font fb=new Font(“TimesRoman”, Font.BOLD, 36);String msg[ ]={“java”, “Portable”, “Secure”, “Easy”};Color color[ ]={Color.blue,Color.yellow,Color.green,Color.red};
public void paint(Graphics g){// called by Run time Libg.setFont(fb);g.setColor(color[i]);g.drawString(msg[i],x,y);
}static public void main(String s[]) throws Exception{
myframe mf= new myframe();mf.setSize(200,200);int pixelsPerLine=200, totalLines=4;mf.setVisibble(true);
//Rolls colored text across the screenstatic public void main(String s[]) throws Exception{
myframe mf= new myframe();mf.setSize(200,200);int pixelsPerLine=200, totalLines=4;mf.setVisibble(true);for (int j=0; j<pixelsPerLine;j++){
Thread.sleep(25);mf.repaint();if (LtoR==1) {
if ( x+=3) < 200) continue;i=++i % 4; // move index to next msg/colorx=50;y=0; LtoR=0;
} else {if (y+=3 < 200) continue;i= ++i % 4;x=0; y=120, LtoR=1;// move message L to R Next time
}}//for
}//main} //myframe class
How to Compile… Run?
• Get Java kit JDK/SDK form Sun
• javac is Java Compiler
• java is Java class file executer (JVM)
• Save it as myframe.java
• Javac myframe.java (compiling….)
• Output myframe.class file
• Run as java myframe <enter>
The biggest Java BenefitJava Portability
• Java executables run on all Computers
• Compile once run it anywhere• Windows, Mac, Unix, IBM’s
mainframe, Cell Phones, PDA, Smart cards (credit cards with a microprocessor and memory)
• Java Portability poses a real threat to Microsoft
• Why software portability matters?• MS Office 95,97,2003,XP,2007
are incompatible• For Distributed processing over
internet portability is Must (Cloud computing)
• IBM is a strong supporter of Java has 6 incompatible products (Mainframes, Minicomputers, workstations, two kinds of PC and a network computer)
• Portability offers more choice• Software portability is about
future proofing your software
How Java is Simpler than C/C++Java does not have…
Compared with C• Memory Address
(pointer) arithmetic• Preprocessor• Automatic Type
Conversion• Global Functions and
variables• typedefs
Compared with C++• Operator Overloading• Multiple Inheritance• Multiple ABIs (Application
Binary Interface: This is the environment that a program sees at run time e.g format of Executable file; Process address space; hardware details like number, sizes of registers.
Data Types
Primitive Type Size (bit) Min Max Wrapper Type
boolean 1 - - Boolean
char 16 Unicode 0 Unicode 2(16)-1 Character
byte 8 -128 +127 Byte
short 16 -2(15) + 2(15)-1 Short
int 32 -2(31) +2(31)-1 Interger
long 64 -2(63) +2(63)-1 Long
float 32 IEEE754 Float
double 64 IEEE754 Double
void - -
What are BigInteger and BigDecimal?
Where Storage Lives
• Registers: CPU• The Stack: This lives in the General RAM
area. Direct Support via Stack Pointer. JVM Know Exact Size, Life time of data to store on stack. Limits on the Flexibility
• The Heap: General Purpose pool of memory in RAM area. Java Objects lives there and give flexibility. “new keyword” Takes more time to allocate Heap storage
• Static storage: In a fixed loaction (RAM). Available for the entire time a programme is running.
• Constant Storage: they can never change• Non-RAM Storage: If data lives completely
outside a program it can exist while program is not running. Streamed objects (streams of bytes), persistent objects (objects placed on disk so they hold their state even when the program is terminated.
Scope and Life Time
Class Scope {
public static void main(String args[ ]){
int x;
x=10;
if (x=10){ //start new scope
int y=20;
x=x+y; // both x, y are know here
// int x=30; // Compile error
System.out.println(“ x and y : ” +x + “ “ + y);
}
// y=100; // Compile error
System.out.println(“ x is= ” +x);
}
}
Type Conversion and castingRule 1: The two types are CompatibleRule 2: The Destination type is larger then the source type Widening Conversion
e.g. int type is larger enough to hold valid byte, short int a;byte b;b= (byte) a; // narrowing conversion
Char and Boolean types are not Compatible with each other and numeric typesbyte a=40;byte b=50;byte c=100;int d= a* b * c;b=b * 2; // Error b=(byte) (b * 2);Java automatically PROMOTES each byte and short operands to int while evaluating an expression.a* b -> is performed using intIf one operand is long then the whole expression is promoted to long
ArraysLength property, Array Index out of Bound Exception
double nums[ ]= { 10.1, 11.2, ……. 15.5 }int twoD [ ] [ ]= new int [4] [5]; OR int [ ] [ ] twoD = new int [4] [5];
Equal Lengthint twoD [ ] [ ]= new int [4] [ ]; for (int i=0; i<4 i++)
twoD[0]= new int [5]; for (int j=0; j<5 j++) {…..}twoD[1]= new int [5];twoD[2]= new int [5];twoD[3]= new int [5];
Variable Length
int twoD [ ] [ ]= new int [4] [ ]; for (int i=0; i<4 i++)twoD[0]= new int [1]; for (int j=0;j< towD[i].length; j+
+)twoD[1]= new int [2]; {……..}twoD[2]= new int [3];twoD[3]= new int [4];
The ‘static’ data, method, block & class
static data: • It belongs to the Class level, not an individual object level.• Exactly one instance of static data exist• Static data means “Only one for the whole class”class Employee{
String name;long salary;short employee_Id;static int total_employee; // per-class field
……} class StaticTest { static int i=47;}
StaticTest st1=new StaticTest();// In some other class or mainStaticTest st2=new StaticTest();
both st1.i and st2.i have the same value 47; ref to same memory.bit confusing the better way is StaticTest.i++;
Static methods:
• Static methods also called class methods that do some class-wide operations
• They operates on Static Data• Unlike per-instance methods they do not apply to an individual
object • ClassName.MethodName() • or ObjectRef.MethodName() is ConfusingClass Employee{
String name;long salary;short employeeId;static int total_employee; // per-class fieldstatic void clear(){ total_employee=0; }static void newHire(){ total_employee++; }……}
Objref.newHire(); //confusingEmployee.newHire();// better: ref through the class name
Static Blocks:• A block of code is a series of statements contained in a pair of {…..}• Inside a Class and outside all methods• static block belongs to a class• Static blocks can only access static dataClass Employee{
String name;long salary;static int total_payroll;static {
System.out.println(“Processing Payroll total “);if (condition) total_payroll=….//some valueelse total_payroll=….//some value }
…} It is executed once when class is first loaded into the JVM. Loading a class
means reading in and converting a stream of bits from a file or URL into as known class inside the JVM. A class is loaded on demand when another class refrences it.
The bug was fixed in JDK 1.2Classes are guaranteed not to be Unloaded unless the class that loaded them is also Unloaded.
Static Classes:• Static class also known as “Nested Top
Level Class”• A static class is just a declaration of an
entire class:– Constructers– Methods– Fields etc.
as a Static member of another classA nested top level class is typically used as
a handy way to group some related classes more tightly together.
Static Class Java Run Time Lib:Netsed Entry class is used to organization that Everything to do with a hashtable
entry is put into the nested class, and any thing to do with the hashtable as a whole is in the hashtable Class.
class Hashtable{private Entry[ ] myTable; //FORWARD REFERENCE to nested classprivate int count=0;Object get(){ return myTable[--count];}void put(Object key, Object val){
Entry e= new Entry(key,Val); myTable[count++]=e;
}static class Entry{ // Nested top level class
int hash;Object key, data;Entry(Object k, Object v) { //Constructor.}int hashCode(){…….}
} // end of nested class ‘Entry’ …..// other methods of hashtable class
}Outside Access:Hashtable.Entry hEntry = new Hashtable.Entry(myKey, MyVal);
int Hcode =hEntry.hashCode();
ArithmeticBitwiseRelationalAnd logical
Operators
Arithmetic+ add- subtract* multiply/ div% mod= assign
Shorthand+= add assign-= sub assign*= mult. assign
/= div assign%= mod assign++ increment-- decrement
You can not use them on boolean types
Bitwise~ Not& AND| OR^ XOR
<< Shift left>> Shift Right>>> Shift right Zero fill
Shorthand>>=>>>=
<<=~=&=|=^=
All integer types except char are signed integers.
High order bit is SIGN bit (1=negative or 0=Positive)
Java use two’s compliment encoding to store negative numbers.
byte b= 42 0010 1010
byte c= -42 1101 0101 (~b) add 1 = 1101 0110int a=3 // 0011 in binary
int b= ~a & 0x0f; // (0000 1111 in binary)
What is ? System.out.print(b)= ?
In bitwise operations turning On high bit to 1 will cause the resulting value to be interpreted as a negative number.
Bitwise<< Shift left(Each time you shift a value to left it double the value)
Example:
int val = 0xFFFFFFE;
val<<=1;
val<<=1;
val<<=1;
val<<=1;
val is NOW negative value
F F F F F F E
Val= 0000 1111 1111 1111 1111 1111 1111 1110
Val= 0001 1111 1111 1111 1111 1111 1111 1100
Val= 0011 1111 1111 1111 1111 1111 1111 1000
Val= 0111 1111 1111 1111 1111 1111 1111 0000
Val= 1111 1111 1111 1111 1111 1111 1110 0000
-ve of (take compliment (~val)+ add 1)
0000 0000 0000 0000 0000 0000 0001 1111
+ 0000 0000 0000 0000 0000 0000 0000 0001
-ve of 0000 0000 0000 0000 0000 0000 0010 0000
val is -32
Bitwise>> Shift Right
>>> Shift right
Zero fill
Each time you shift a value to the right it divides that value by 2 (discard the remainder)
+8 -> 0000 1000 >> 1
+4 = 0000 0100
-8 -> 1111 1000 >> 1
-4 = 1111 1100
Right Shifting is with Sign extension i.e. it preserve the sign of negative numbers during right shift.
What will you get if you right shift -1
int a= -1;
a>>=24; = ?
The unsigned right shift is a special case of right shift which is designed for non numeric values like working on some pixel-based values and graphics coordinates.
Unsigned right shift fills Zero into the high-order bit.
int a= -1;
-> 1111 1111 1111 1111 1111 1111 1111 1111
a>>>=24;
-> 0000 0000 0000 0000 0000 0000 1111 1111= 255
Logical boolean Operators&,|,^,!Short-circuit && logical|| logical
The outcome of these operators is boolean value.
== equal, != not equal, <, <=, >, >=
Testing Object Equivalence:
Class TestValue{
int i;
}
Public class Test{
public static void main(String a[ ]){
Integer n1=new Integer(127);
Integer n2=new Integer(127);
System.out.println(n1==n2); //1
System.out.println(n1!=n2);// 2
System.out.println(n1.equals(n2));// 3
TestValue v1= new TestValue();
TestValue v2=new TestValue();
v1.i=v2.i=100;
System.out.println(v1.equals(v2));//4
}
}
Control Statementsif(condition){…}if(condition){….} else {….}if(condition){..} else if(cond2) {..} else {….}
switch(exp1){ case val1:Statements; break;//jump outcase val2:Statements; break;default:
Statements;}
while(cond1){……}do{……} while(cond1)
for(init;condition;iteration){……}for(i=0,j=5;i<j;i++,j--){…….} //two control vari=comlexExpression();for( ;!flag;) {…. flag=true;…i+=nonSequentialWay()…..} // complex stylefor ( ; ; ){ infinite loop }
Using break as a form of Gotolabel1{
label2:{label3:{
if(true) break label2;}
statements1 // will not execute}statements2
}
SECTION-A
Completed
• An application is created from classes. • A class is similar to a struct in the C language in that it
stores related data in fields, where the fields can be different types. So you could, for example, store a text string in one field, an integer in another field, and a floating point in a third field. The difference between a class and a struct is that a class also defines the methods to work on the data.
• For example, a very simple class might store a string of text and define one method to set the string and another method to get the string and print it to the console. Methods that work on the data are called accessor methods.
• Every application needs one class with a main method. This class is the entry point for the program, and is the class name passed to the java interpreter command to run the application.
• The code in the main method executes first when the program starts, and is the control point from which the controller class accessor methods are called to work on the data.
class ExampleProgram { public static void main(String[] args){
System.out.println("I'm a Simple Program"); }
}
• The public static void keywords mean the Java virtual machine (JVM) interpreter can call the program's main method to start the program (public) without creating an instance of the class (static), and the program does not return data to the Java VM interpreter (void) when it ends.
• An instance of a class is an executable copy of the class While the class describes the data and behavior, you need a class instance to acquire and work on data. The diagram shows three instances of the ExampleProgram class by the names: FirstInstance, SecondInstance and ThirdInstance.
• The main method for the simple example does not create an instance of the ExampleProgram class because none is needed. The ExampleProgram class has no other methods or fields, so no class instance is needed to access them from the main method. The Java platform lets you execute a class without creating an instance of that class as long as its static methods do not call any non-static methods or fields.
• The ExampleProgram class just calls System.out.println. The java.lang.System class, among other things, has a static out field of type PrintStream that is used to invoke the println methods in the PrintStream class.
class LessonTwoB { String text = "I'm a Simple Program"; static String text2 = "I'm static text"; String getText(){ return text; }String getStaticText(){ return text2; }public static void main(String[] args){ LessonTwoB progInstance = new LessonTwoB(); String retrievedText = progInstance.getText(); String retrievedStaticText =
progInstance.getStaticText(); System.out.println(retrievedText);
System.out.println(retrievedStaticText); }
}
class LessonTwoC { static String text = "I'm a Simple
Program"; //Accessor method
static String getText(){ return text; } public static void main(String[] args){
String retrievedText = getText();
System.out.println(retrievedText); } }
class methods can operate only on class fields, and instance methods can operateon class and instance fields
Important Note:• Object variables holds refrence to objects not Objects• Declaring an object variable does not create a corresponding object• Comparing two object variables with == opeartor really compares
the pointes held in the variables, not the objects pointed to.• An object is passed as a parameter by pushing a copy of the
reference to it on the stack• It is easy to declare a class that has an instance of itself as a field
e.g. Linklist, binary tree contains two binary trees– Class bTree{ class Node {
bTree left; int info;bTree right; Node ptr; } }
• A reference variable is DEreferenced automatically to get the contents of fields in the Object. But remember that assignments and comparisons are of pointes, not Objects
Constructors
Constructor is like a special kind of method that can be used only to create and initialize a new object.
Constructor functions always have the same name as the class
Access_Modifiers Classname(param) optional_throws{.....}
No return type
Constructorclass LessonTwoD { String text; //Constructor LessonTwoD(){
text = "I'm a Simple Program"; } //Accessor method String getText(){
return text; } public static void main(String[] args){
LessonTwoD progInst = new LessonTwoD(); String retrievedText = progInst.getText(); System.out.println(retrievedText); }
}
Constructor and “this”class LessonTwoD { String text; //Constructor LessonTwoD(){
this("I'm a Simple Program“); } LessonTwoD(String s){
text =s;} //Accessor method String getText(){ return text; } public static void main(String[] args){
LessonTwoD progInst = new LessonTwoD(); String retrievedText = progInst.getText(); System.out.println(retrievedText); }
}
Garbage collection (GC)The automatic reclaiming of memory that is no longer in use is called
GC in java. Java has a runtime storage manager and one sub system of storage
manages is called GC. Java has a thread in the background whose task is to do GC It looks at the memory and when it finds objects that are no longer
refrenced, it reclaims them by telling the heap that memory is available to reuse.Languages with dynamic data structures need more memory we do that like
malloc() in C, “new” in JavaTo reuse/freeing
free() in C, Java approach is GC Why GC?Memory Leak: • Its all too easy to create a memory leak by not freeing memory
before overwriting last pointer to it.• It can then neither be referenced nor freed and that amount of
memory is lost to further use for as long as the program runs
Garbage collection (GC)GC Algorithms
Reference Counting: Keeps a counter for each chunk of memory allocated.
Adv: steady constant overhead
Dis-Adv:
1) A -> B and B -> A, nothing else point to A and B, Then reference count of A and B >0 Hence A, B will not be free.
2) Ref. Count must be locked for Mutual exclusion in multi-threading
Garbage collection (GC)Mark & Sweep
The marker start from the root and mark (say red) every object that is reachable.
Then sweep phase starts, everything not marked (not red) swept back to free space.
Stop & copy:
Stops all other threads completely
The heap is split into two parts: the Current active part and the new part called “semi-space”. It copy all non-garbage stuff to new semi-space and at the end current active space is just discarded completely.
Garbage collection (GC)Protected void finalize(){
//Action about to reclame memory
}
Method Overloading class Tree{
int height;Tree(){
prt(“Planting a Seedling”);height=0; }
Tree(int i) {prt(“Creating new Tree of “ + i + “feet”);height=i; }
void info(){ prt(“Tree of “ + i + “ feet”);}void info(String s){ prt(s+“: Tree of “ + i + “ feet”);}static void prt(String s){
System.out.println(s);}
}// class Tree ends
Method Overloading Public class Test{
public static void main(String[] args){for (int i=0;i<5; i++){
Tree t=new Tree(i)t.info();t.info(“Overloaded method”);}
//overloaded constructornew Tree();
}}// class ends
Method Overloading Order Public class Test{
static void print(String s, int i){System.out.println(“String: “ + s + “, int:”+i)
}static void print(int i, String s){
System.out.println(“int:”+ i + “String: “ + s )}public static void main(String[] args){
print(“String first arg”, 10);print(11,”String Second arg”);
}}// class ends
Overloading with Return typesvoid f() { …}int f() {….}Object f() {…..}Consider the call
int x = f(); Calling a method for its Side effect i.e. don’t care return type
f();Which f()????
This keyword Public class Banana{
void f(int i){ … }
void f2(){ f(10); …} // not this.f(10)
Banana getB() { return this;}
}// class ends
….
Banana a new Banana(), b=new Banana();
a.f(1); === Banana.f(a,1);
b.f(2); = Banana.f(b,2);
Java Initialization Java provide guaranteed initialization. Even though the values are not specified they
automatically get initialized.Data type Initial value
boolean falsechar null charbyte 0short 0int 0long 0float 0.0double 0.0
Object references are initialized to null pointerclass TestInit{
int k;boolean flag=true;Myclass o= new Myclass();int i= f();int j=g(i);
// int j=g(i);// int i=f();
}
Order of Initializationclass Tag{
Tag(int marker){System.out.println(“Tag(“+marker+”)”);
}}class Card {
Tag t1=new Tag(10); Card() {
System.out.println(“CARD()”);t3= new Tag(33); // re-initialize
}Tag t2=new Tag(2);void f(){
System.out.println(“f()”);}Tag t3= new Tag(3);
} public class InitTest{
public static void main(String[] arg){Card c=new Card();c.f();
}}
OUTPUT=?
Order of Initializationclass Tag{
Tag(int marker){System.out.println(“Tag(“+marker+”)”);
}}class Card {
Tag t1=new Tag(1); Card() {
System.out.println(“CARD()”);t3= new Tag(33); // re-initialize
}Tag t2=new Tag(2);void f(){
System.out.println(“f()”);}Tag t3= new Tag(3);
} public class InitTest{
public static void main(String[] arg){Card c=new Card();c.f();
}}
OUTPUTTag(10)Tag(2)Tag(3)
Order of Initializationclass Tag{
Tag(int marker){System.out.println(“Tag(“+marker+”)”);
}}class Card {
Tag t1=new Tag(1); Card() {
System.out.println(“CARD()”);t3= new Tag(33); // re-initialize
}Tag t2=new Tag(2);void f(){
System.out.println(“f()”);}Tag t3= new Tag(3);
} public class InitTest{
public static void main(String[] arg){Card c=new Card();c.f();
}}
OUTPUTTag(10)Tag(2)Tag(3)CARD()Tag(33)f()
Access Specifierpublic: everybody, everywhere, can access it.<no access modifier>: Make the member friendly by leaving off any access specifier. The other classes only in the same package can access it. package accessprotected: Inherited classes can access a protected member as well as public members. No private members. It can access friendly members only if the two are in the same package.private: Members are not accessible outside the class.
Access SpecifierNote:
1. Making a constructor private prevents the class being instantiated
2. Making a member private means it can only be called from within the class
3. Protected is Less protected as protected members are accessible in the package and in subclasses of the class. Protected in Java is automatically friendly
4. A class can be given a package or public access
Final ModifierFinal makes something constant
final static int myMax= 99999;final Fruit banana= new Fruit();
If reference variable is declared final, it menas that you cannot make that variable point to some other object
By using final reference variable you can change the object values.Reference is final, not the reference object
void f(final Fruit o, final int a[]){o.color=‘red’;a[0]=100;o=new Fruit();a=new int[130];
}NOTE: final is a clue to the compiler that certain optimizations can be made.In case of final primitive data the compiler can substitute the value at each
place The blank final variable initialized only once (jdk 1.1) final String consumer;
Assignment-2
• What is AWT?
• Introduction to AWT Classes
• What are Jcomponents?
• Write a Java Program for drawing:– text,– Lines and– Shapes
Inheritance Vs Composition• Compositions generally used when you want the features of an
existing class inside your new class but not the interface.• During composition you embed an object so that you can use it to
implement the features of your new class, but the user of your new class sees the interface you have defined rather than the interface from the embed object. For this effect you embed PRIVATE objects of existing classes inside your new class.
• The “has-a” relationship is expressed with composition• When you inherit, you take an existing class and make a special
version of it. In general, this means you are taking a general-purpose class specialized it for a particular need.
• The “is-a” relationship is expressed with inheritance.• Both inheritance and composition allow you to place sub-objects
inside your new class.• It is very common to use composition with inheritance
//Car.javaclass Engine{public void start(){ }public void rev(){ }public void stop(){ }
}class Wheel{
public void air (int psi){ }}class Window{
public void rollup (){ }public void rolldown (){ }
}class Door{
public Window o=new Window();public void open (){ }public void close (){ }
}
public class Car{public Engine engine=new Engine();public Wheel[ ] wheels= new Wheel[4];public Door left= new Door(),
right=new Door();Car(){
for (int i=0; i<4;i++)wheels[i]=new Wheel();
}
public static void main(String s[]){Car car=new Car();car.left.window.rollup();car.wheels[0].air(32);}
}With a little thought, you will see that it
would make NO sense to composite a car using a vehicle object. A car does not contain a vehicle, it “is-a” vehicle.
Constructors with argumentsclass Game {
Game(int id) {System.out.println(“Game
Constructor”);}
}class BoardGame extends Game {
BoardGame(int id){super(id);System.out.println(“BoardGame”);}
}public class Chess extends BoardGame{
chess(){super(101);System.out.println(“Chess”);
}public ststic void main(String s[]){
Chess obj= new Chess();}
}
• If you do not call the base class contractor in BoardGame(), the Compiler will complain that it cannot find a constructor of the form Game()
• The call to the base class constructor must be the first thing you do in the derived class constructor
Up casting
• Inheritance is the relationship expressed between the new class and the base class
• The relationship is “the new class is a type of the existing class”
• Instrument Class represent all musical instruments
• Wind class derived from Instrument Class• Play() method of Instrument become Wind
Instruments• Wind object is also a type of Instrument.
Up castingclass Instrument{public void play(){ }static void tune(Instrument i){//i.play();}
}Class Wind extends Instrument{
public static void main(String s[]){Wind flute=new Wind();Instrument.tune(flute); // Upcasting}
}Wind Object is also an Instrument Object.Inside tune() method the code works for Instrument and anything derived
from Instrument, and the act of converting a Wind type pointer into an Instrument type pointer is called Up-casting
Up casting
Instrument (more general Type)
(casting from derived to base)
Wind (more Specific Type)
Up casting always safe.
Compiler allows upcasting without any explicit casts or other special notation
Final Methods
• Preventing any inheriting class to change its meaning
• The method can not be overridden
• Second efficency, compiler can turns any calls to final method into inline calls.
• Any private methods in a class are implicitly final.
Final class
• When you say that entire class is final class, you state that you do not want to inherit from this class or allow any one else to do so.
• When there is never a need to make any changes or for safety or security you do not want subclassing.
• Declaring a class final simply prevents inheritance, however because it prevents inheritance all methods in a final class are implicitly final, since there is no way to override them.