FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit...

55
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 1 Unit Inheritance and sub classing in Java and packages and use of access specifiers Sr. No Topic Page No. 2.1 What is inheritance 3 Definition : Inheritance Single Inheritance 2.2 Inheritance in Java 3 to 9 Defining Subclasses Inheritance Basics Types of Inheritance Simple Inheritance Multilevel Inheritance 2.3 Method Overriding 10 to 12 2.4 Method Overloading Vs Method Overriding 13 to 15 2.5 Uses of super keyword 16 to 19 Variable Shadowing and the use of super keyword Use of super to call super class constructor Method overriding and the use of super keyword 2.6 When Constructors Are Called ? 19 to 20 2.7 Dynamic Method and Variable Binding (Dispatch) 21 to 22 2.8 Using final with variables, methods and classes 22 to 24 OR Uses of final keyword final Variables final Methods final Classs 2.9 abstract classes and abstract methods 24 to 26 OR Uses of abstract keyword 2.10 Interfaces 26 to 36 Defining interfaces Implementing interfaces Variables in Interfaces Single Inheritance of Interfaces ( Interfaces Can Be Extended )

Transcript of FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit...

Page 1: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 1   

 

Unit   Inheritance and sub classing in Java and packages and use of access specifiers 

Sr. No  Topic                    Page No.   2.1        What is inheritance        3  

• Definition : Inheritance 

• Single Inheritance 

2.2       Inheritance in Java   3  to 9 

• Defining Subclasses 

• Inheritance Basics 

• Types of Inheritance  Simple Inheritance  Multilevel Inheritance 

2.3  Method Overriding                10  to 12 

2.4  Method Overloading    Vs     Method  Overriding        13  to 15 

2.5       Uses of   super    keyword  16  to 19 

• Variable Shadowing and the use of   super   keyword 

• Use of super to call super class constructor 

• Method overriding and the use of super keyword 

2.6  When Constructors Are Called ?            19  to 20 

2.7  Dynamic Method and Variable Binding (Dispatch)        21  to 22 

2.8  Using final with variables, methods and classes        22  to 24 

                           OR   

              Uses of   final    keyword • final  Variables 

• final  Methods 

• final  Classs 

2.9  abstract classes and abstract methods          24  to 26 

                           OR   

              Uses of   abstract    keyword 2.10  Interfaces                  26  to 36 

• Defining interfaces 

• Implementing interfaces 

• Variables in Interfaces  

• Single Inheritance of Interfaces  ( Interfaces Can Be Extended ) 

Page 2: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 2   

 

• Accessing Implementations Through Interface References (optional) 

• Partial Implementations  (optional) 

2.11  Abstract classes    Vs    interfaces            37  to 40 

2.12  Package                  41  to 55 

• Defining package 

• Importing Packages 

• Use of static imports 

• Use of  CLASSPATH   for   class   loading 

• Access protection / Access Specifiers  Access specifiers for members of a package  Access specifiers for members of a class  Access specifiers for overriding methods  

   

Page 3: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 3   

 

2.1        What is inheritance    

• Definition : Inheritance 

• Single Inheritance 

Inheritance   –  As a OOP Concept  

• Inheritance in OOP allows to define a general class and later to organize some other classes simply adding some details with the old class definition.  

• This saves work as the special class inherits all the properties of the old general class and as a programmer you only require the new features.  

• This helps in a better data analysis, accurate coding and reduces development time.  • This is the mechanism of organizing and structuring software program.  • Though objects are distinguished from each other by some additional features but there are objects that 

share certain things common.  • In object oriented programming classes can inherit some common behavior and state from others.  

 Single Inheritance 

• When a class inherits from only one class, it is called single inheritance.   

2.2       Inheritance in Java   

• Defining Subclasses 

• Inheritance Basics 

• Types of Inheritance  Simple Inheritance  Multilevel Inheritance 

Inheritance – Implementation in JAVA  

• Using inheritance, you can create a general class that defines traits common to a set of related items.  • This class can then be inherited by other, more specific classes, each adding those things that are unique to 

it.  • In the terminology of Java, a class that is inherited is called a   superclass. The class that does the inheriting 

is called a   subclass.  • Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and 

methods defined by the superclass and adds its own, unique elements. • As the name suggests, inheritance means to take something that is already made. It is the concept that is 

used for reusability purpose. • Inheritance  supports  the concepts of hierarchical classification. 

 

DEFINING SUBCLASSES • The general form of a class declaration that inherits a superclass is shown here:  

SYNTAX :‐     

class subclass_name extends superclasses_name    {      Body of class    }    

Page 4: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 4   

 

Note: • You can only specify one superclass for any subclass that you create.  • Java does not support the inheritance of multiple superclasses into a single subclass. (This differs from C++, 

in which you can inherit multiple base classes.)  • You can, as stated, create a hierarchy of inheritance in which a subclass becomes a superclass of another 

subclass. • However, no class can be a superclass of itself. 

  

 Inheritance Basics 

• To  inherit  a  class,  you  simply  incorporate  the  definition  of  one  class  into  another  by  using  the  extends keyword.  

• The  following  program  creates  a  superclass  called  A  and  a  subclass  called  B.  Notice  how  the  keyword extends is used to create a subclass of A. 

Page 5: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 5   

 

Example: SimpleInheritance.java  class A  { 

int i, j; void showij()  { 

System.out.println("i and j: " + i + " " + j); } 

} 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(); 

} }    

Page 6: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 6   

 

Output: 

Contents of superOb: i and j: 10 20 Contents of subOb: i and j: 7 8 k: 9 Sum of i, j and k in subOb: i+j+k: 24 

 Example:  public class Bicycle  {     // the Bicycle class has three fields     public int cadence;     public int gear;     public int speed;     // the Bicycle class has one constructor     public Bicycle(int startCadence, int startSpeed, int startGear)      {         gear = startGear;         cadence = startCadence;         speed = startSpeed;      }        // the Bicycle class has four methods     public void setCadence(int newValue)      {         cadence = newValue;     }     public void setGear(int newValue)      {         gear = newValue;     }     public void applyBrake(int decrement)      {         speed ‐= decrement;     }     public void speedUp(int increment)      {         speed += increment;     } } public class MountainBike extends Bicycle  {     // the MountainBike subclass adds one field     public int seatHeight;      // the MountainBike subclass has one constructor 

Page 7: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 7   

 

    public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear)     {         super(startCadence, startSpeed, startGear);         seatHeight = startHeight;     }       // the MountainBike subclass adds one method     public void setHeight(int newValue)     {         seatHeight = newValue;     }   }  The following kinds of inheritance are there in java. 

  Simple Inheritance     Multilevel Inheritance 

Pictorial Representation of Simple and Multilevel Inheritance 

                               Simple Inheritance 

                          Multilevel Inheritance 

 

Simple Inheritance  • When a  subclass is derived simply from it's parent class then this mechanism is known as simple 

inheritance.  • In case of simple inheritance there is only a sub class and it's parent class. It is also called single 

inheritance or one level inheritance.                                               • Example.  

class A  {   int w;   int x;   void  set(int p, int q)   {     w=p; x=q;    }   void Show()   {       System.out.println(w);       System.out.println(x);     } }  

Page 8: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 8   

 

class B extends  A  {   int y;   void  set(int   r)   {     y=r;    } void Show()   {       System.out.println(w);       System.out.println(x);       System.out.println(y);   } } class DemoSimple{   public static void main(String args[]){     A a = new A();     a.set(5,6);     a.Show();          B b = new B();     b.set(7);     b.Show();   } } Multilevel Inheritance 

• It is the enhancement of the concept of inheritance.  • When a subclass is derived from a derived class then this mechanism is known as the multilevel 

inheritance.  • The derived class is called the subclass or child class for it's parent class and this parent class works 

as the child class for it's just above ( parent ) class.   • Multilevel inheritance can go up to any number of level. 

 Example: class A  {   int w;   int x;   void  set(int p, int q)   {     w=p; x=q;    }   void Show()   {       System.out.println(w);       System.out.println(x);     } }  

Page 9: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 9   

 

class B extends  A  {   int y;   void  set(int   r)   {     y=r;    } void Show()   {       System.out.println(w);       System.out.println(x);       System.out.println(y);   } }  class    C  extends   B {   int z;   void  set(int   s)   {     z=s;    } void Show()   {       System.out.println(w);       System.out.println(x);       System.out.println(y);       System.out.println(z);   } } class DemoMultiple{   public static void main(String args[]){     A a = new A();     a.set(5,6);     a.Show();          B b = new B();     b.set(7);     b.Show();         C c = new C();     c.set(8);     c.Show(); 

  } } 

Note : Java does not support multiple Inheritance 

Page 10: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 10   

 

2.3  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 with a subclass object, 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.  

 // 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 OverrideDemo  { 

public static void main(String args[])  { 

Page 11: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 11   

 

B  subOb = new B(1, 2, 3); subOb.show(); // this calls show() in B 

} } Output:   k: 3  

Note : When show( ) is invoked on an object of type B, the version of show( ) defined within B is used. That is, the version of show( ) inside B overrides the version declared in A.  

Applying Method Overriding  // 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()  { 

Page 12: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 12   

 

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()); 

} } Output: Inside Area for Rectangle. Area is 45 Inside Area for Triangle. Area is 40 Area for Figure is undefined. Area is 0 

 

Why Overridden Methods? • Overridden methods allow Java to support run‐time polymorphism. • Polymorphism is essential to object‐oriented programming for one reason: it allows a general class to 

specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods.  

• Overridden methods are another way that Java implements the “one interface, multiple methods” aspect of polymorphism.  

• Part of the key to successfully applying polymorphism is understanding that the superclasses and subclasses form a hierarchy which moves from lesser to greater specialization.  

• Used correctly, the superclass provides all elements that a subclass can use directly. It also defines those methods that the derived class must implement on its own.  

• This allows the subclass the flexibility to define its own methods, yet still enforces a consistent interface. Thus, by combining inheritance with overridden methods, a superclass can define the general form of the methods that will be used by all of its subclasses.  

• Dynamic, run‐time polymorphism is one of the most powerful mechanisms that object‐oriented design brings to bear on code reuse and robustness. The ability of existing code libraries to call methods on instances of new classes without recompiling while maintaining a clean abstract interface is a profoundly powerful tool. 

  

Page 13: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 13   

 

2.4  Method Overloading    Vs     Method  Overriding    Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded.   For example, consider this modified version of the preceding example: // Methods with differing type signatures are overloaded – not  overridden. 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); } 

} // Create a subclass by extending class A. class B extends A  { 

int k; B(int a, int b, int c)  { 

super(a, b); k = c; 

} // overload show() void show(String msg)  { 

System.out.println(msg + k); } 

} class Override  { 

public static void main(String args[])  { 

B subOb = new B(1, 2, 3); subOb.show("This is k: "); // this calls show() in B subOb.show(); // this calls show() in A 

} } Output: This is k: 3 i and j: 1 2 

   

Page 14: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 14   

 

Difference between :  Method Overloading   and     Method  Overriding 

Method Overloading  

• Method overloading means having two or more methods with the same name but different signatures in the same scope.  

• These two methods may exist in the same class or anoter one in base class and another  in derived class. • Overloading may occur  with a single class or respect to inheritance also.  •  In side the class you can write multipul method with the same name this is called method overloading. 

 When you overloading the methods you need to change the parameters as follows a)Number of parameter b)Type of parameter c)Order of parameter 

• When you are overloding the method return type of the method can be any type. • For example   

void method( int i, int j) void method( int i, int j, int k )   

are overloaded as they differ in number of parameters..  void method() int method()  

are not overloaded as return‐type alone is insufficient to distinguish the method having the same name..  

• Overloading. is compile time,  while  and overriding is run time 

• In overriding case,  you must extends super class,   while overloading  is possible with same class also.  

Method Overriding: 

• Method overriding means having a different implementation of the same method in the inherited class.  • These two methods would have the same signature, but different implementation. One of these would exist 

in the base class and another in the derived class.  • These methods cannot exist in the same class. • Overriding occurs only with respect to inheritance and occurs when a child has a method with the same 

signature as a parent's method.  • overloading. is compile time  

and overriding is run time 

• Overloading. is compile time,  while  and overriding is run time 

• In overriding case,  you must extends super class,   while overloading  is possible with same class also. • The return type, method name, type and order of arguments must be identical to those of a method in a 

parent class. 

• The accessibility must not be more restrictive than original method. • For example   

  

Page 15: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 15   

 

class Superclass { void show() { } } class Subclass extends Superclass { void show() { } } 

Example: Method Overloading and Method Overriding 

//Please clarify the difference  class A { 

void calc() { } int calc(int) { } 

} class B extends   A { 

void calc() { } 

} class  Demo {   A  a   =  new A();   a.calc();   // this will call class A  calc() method   with no argument// Method ovrloading   B  b    =   new   B();   b.calc();                 // this will call class B  calc() method  // Method ovrriding }  

 

   

Page 16: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 16   

 

2.5       Uses of   super    keyword • Variable Shadowing and the use of   super   keyword 

• Use of super to call super class constructor 

• Method overriding and the use of super keyword 

super keyword 

• The super is java keyword. As the name suggest super is used to access the members of the super class. • It is used for two purposes in java. 

o Variable Shadowing and the use of   super   keyword /  Toc access member of a super class o Use of super to call super class constructor o Method overriding and the use of super keyword 

 

Variable & Method  Shadowing and the use of   super   keyword 

• We can access the super class members inside the subclass class just by calling the following command. 

super.member; 

Here member can either be an instance variable or a method.  

• This form of super most useful to handle situations where the local members of a subclass hides the members of a super class having the same name.  

• The following example clarify all the confusions.  

class A {     int a;     float b;     void Show() 

{         System.out.println("b in super class:  " + b);     } }  class B extends A {     int a;      float b;     B( int p, float q)     {         a = p;         super.b = q;     }      

Page 17: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 17   

 

void Show()     {         super.Show();         System.out.println("b in super class:  " + super.b);         System.out.println("a in sub class:    " + a);     } } class  DemoSuperMemb {     public static void main(String[] args)     {         B subobj = new B(1, 5);         subobj.Show();     } } 

Output: 

C:\>java B b in super class: 5.0 b in super class: 5.0 a in sub class: 1  

Use of super to call super class constructor:  

• The  keyword super in java can be used to call a super class constructor in the subclass.  • This functionality can be achieved just by using the following command. 

super(param‐list);       Here parameter list is the list of the parameter requires by the constructor in the super class.  

• super must be the first statement executed inside a super class constructor.  • If we want to call the default constructor then we pass the empty parameter list.  • The following program illustrates the use of the super keyword to call a super class constructor.  

class A {     int a;     int b;     int c;     A(int p, int q, int r) 

{         a=p;         b=q;        c=r;     } }  

Page 18: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 18   

 

class B extends A {       int d;       B(int l, int m, int n, int o) 

{           super(l,m,n);           d=o;         }       void Show() 

{           System.out.println("a = " + a);           System.out.println("b = " + b);           System.out.println("c = " + c);           System.out.println("d = " + d);       }        public static void main(String args[]) 

{           B b = new B(4,3,8,7);           b.Show();       }   } Output: C:\>java B a = 4 b = 3 c = 8 d = 7  

Method overriding and the use of super keyword 

• When an overridden method is called from with a subclass object, it will always refer to the version of that method defined by the subclass.  

• If you wish to access the superclass version of an overridden method, you can do so by using super.   

// 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); } 

Page 19: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 19   

 

class B extends A  { 

int k; B(int a, int b, int c)  { 

super(a, b); k = c; 

} void show()  { 

super.show(); // this calls A's show() System.out.println("k: " + k); 

} } Output: i and j: 1 2 k: 3  Note : In this version of B, the superclass version of show( ) is invoked within the subclass’ version. This allows all instance variables to be displayed. Here, super.show( ) calls the superclass version of show( ).  Member Access and Inheritance Note : A class member that has been declared as private will remain private to its class. It is not accessible by any code outside its class, including subclasses. 

 2.6  When Constructors Are Called ?             

Que:     When a class hierarchy is created, in what order are the constructors for the classes that make up the                  hierarchy  called?  Ans :      

• In a class hierarchy, constructors are called in order of derivation, from superclass to subclass. • Further, since super( ) must be the first statement executed in a subclass’ constructor, this order is the same 

whether or not super( ) is used.  • If super( ) is not used, then the default or parameterless constructor of each superclass will be executed.  • For example, 

// Demonstrate when constructors are called. // Create a super class. class A  { 

int I; A( )  { 

System.out.println("Inside A's constructor."); } A(int a) {   i=a; } 

Page 20: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 20   

 

// Create a subclass by extending class A. class B extends A  {   int j; 

B( ) { 

//super(); System.out.println("Inside B's constructor."); 

} B(int a, int b) { 

super(a);            j=b; } 

} // Create another subclass by extending B. class C extends B  {   int k; 

C( )  { 

//super(); System.out.println("Inside C's constructor."); 

} C(int a, int b, int c) {   super(a,b);   k=c; } 

} class CallingCons  { 

public static void main(String args[])  { 

C   c = new C();  C   cobj = new C(11,22,33);  

} } The output from this program is shown here: Inside A’s constructor Inside B’s constructor Inside C’s constructor  

   

Page 21: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 21   

 

2.7  Dynamic Method and Variable Binding (Dispatch)      

• Method overriding forms the basis for one of Java’s most powerful concepts: 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.   • Dynamic method dispatch is important because this is how Java implements run‐time polymorphism. • In Java method binding is done at the run time.  • So the method callme() in below example that will be used is not determined at compile time. Rather, the 

method invocation is determined at the the runtime by the instance on which a method is being invoked. • According to the object assigned to super class(A) reference variable, approriate version of callme() method 

will be called.For eg,  r = new A(5), will call A’s callme() method,    r = new B(6), will call B’s callme() method,   r = new C(7)  will call C’s callme() method . 

 // Dynamic Method Dispatch class A { 

int  x; A(int a) {   x   =  a; } void callme()  { 

System.out.println("Inside A's callme method"); } 

} class B extends A  { 

int  x; B(int a) {   x   =  a; } // override callme() void callme()  { 

System.out.println("Inside B's callme method"); } 

} class C extends A  { 

int  x; C(int a) {   x   =  a; } // override callme() void callme()  { 

System.out.println("Inside C's callme method"); } 

Page 22: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 22   

 

} class Dispatch  { 

public static void main(String args[])  { 

A   a = new   A(5);      // object of type A B   b = new   B(6);     // object of type B C   c = new    C(7);      // 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 System.out.println("x   value for Class A : "+   r.x  );  r = b; // r refers to a B object r.callme(); // calls B's version of callme System.out.println("x   value for Class B : "+   r.x  );  r = c; // r refers to a C object r.callme(); // calls C's version of callme System.out.println("x   value for Class C : "+   r.x  ); 

} } Output: Inside A’s callme method x   value for Class A :  5   Inside B’s callme method x   value for Class B :  6 Inside C’s callme method x   value for Class C :  7 

 

 

2.8  Using final with variables, methods and classes       

• While the examples in the preceding section demonstrate the mechanics of method overriding, they do not show its power.  

 

final Variables 

• A variable can be declared as final. Doing so prevents its contents from being modified. This means that you must initialize a final variable when it is declared. 

• (In this usage, final is similar to const in C/C++/C#.)  • For example: 

final int FILE_NEW = 1; final int FILE_OPEN = 2; final int FILE_SAVE = 3; final int FILE_SAVEAS = 4; final int FILE_QUIT = 5; 

Page 23: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 23   

 

• Subsequent parts of your program can now use FILE_OPEN, etc., as if they were constants, without fear that a value has been changed. 

• It is a common coding convention to choose all uppercase identifiers for final variables.  • Variables declared as final do not occupy memory on a per‐instance basis.Thus, a final variable is essentially 

a constant.   

Using final with Inheritance  OR  (final Methods & final Class) 

final  methods   /    Using final to Prevent Overriding 

• While method overriding is one of Java’s most powerful features, there will be times when you will want to prevent it from occurring.  

• To disallow a method from being overridden, specify final as a modifier at the start of its declaration.  • Methods declared as final cannot be overridden.  • For example: 

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!"); } 

} • Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a compile‐time 

error will result.  • Methods declared as final can sometimes provide a performance enhancement: The compiler is free to 

inline calls to them because it “knows” they will not be overridden by a subclass.  • When a small final method is called, often the Java compiler can copy the bytecode for the subroutine 

directly inline with the compiled code of the calling method, thus eliminating the costly overhead associated with a method call. Inlining is only an option with final methods.   

Late Binding and Early Binding 

• Normally, Java resolves calls to methods dynamically, at run time. This is called late binding. However, since final methods cannot be overridden, a call to one can be resolved at compile time. This is called early binding. 

 

final  class  /  Using final to Prevent Inheritance 

• Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final.  

• Declaring a class as final implicitly declares all of its methods as final, too. • Here is an example of a final class: 

Page 24: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 24   

 

final class A  { 

// ... } // The following class is illegal. class B extends A    // ERROR! Can't subclass A { 

// ... } 

• As the comments imply, it is illegal for B to inherit A since A is declared as final.  

Note :  As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.  

 

2.9  Abstract classes and abstract methods           

Abstract Method • An abstract method one that have the empty implementation.  • Abstract method provides the standardization for the " name and signature" of any method.  • One can extend and implement to these methods in their own classes according to the requirements.    • You can require that certain methods be overridden by subclasses by specifying the abstract type modifier.  • These methods are sometimes referred to as subclasses  responsibility because they have no 

implementation specified in the superclass. • Thus, a subclass must override them—it cannot simply use the version defined in the superclass.  • To declare an abstract method, use this general form:  

 abstract   ret_type  method_name(parameter‐list); 

Note :  All the methods in any interface are abstract by default.  

Abstract Class  • In java programming language, abstract classes are those that works only as the parent class or the base 

class.  • Subclasses are derived to implement the methods inherited from the abstract class (base class).  • Abstract classes are not instantiated directly. First extend the base class and then instantiate (create 

objects).  • Abstract classes are generic in nature and implement to those methods that are used commonly by the 

subclasses with common implementation.  • Sample Example: 

abstract class A {      public abstract void abs_value();          void show() 

{          System.out.println("This is an abstract class");  } 

    } 

Page 25: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 25   

 

•  Example 1 : 

// A Simple demonstration of abstract. abstract class A  { 

abstract void callme();  // concrete methods are still allowed in abstract classes void callmetoo()  { 

System.out.println("This is a concrete method."); } 

} class B extends A  { 

void callme()  { 

System.out.println("B's implementation of callme."); } 

} class AbstractDemo  { 

public static void main(String args[])  { 

A a = new A(); // Incorrect a.callme();     // Incorrect a.callmetoo();   // Incorrect  B b = new B(); b.callme(); b.callmetoo(); 

} } 

• Example 2 : // Using abstract methods and classes. abstract class Figure  { 

double dim1; double dim2; Figure(double a, double b)  { 

dim1 = a; dim2 = b; 

}  // area is now an abstract method abstract double area();  

}   

Page 26: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 26   

 

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   abstractDemo { 

public static void main(String args[])  { 

…………………… } 

}  

2.10  Interfaces                   

• Defining interfaces 

• Implementing interfaces 

• Variables in Interfaces  

• Interfaces Can Be Extended  /  Single Inheritance of Interfaces 

• Accessing Implementations Through Interface References (optional) 

• Partial Implementations  (optional) 

 

 

 

Page 27: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 27   

 

Interface 

• Using the keyword interface, you can fully abstract a class’ interface from its implementation. • That is, using interface, you can specify what a class must do, but not how it does.  • Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are 

declared without any body.  • Once it is defined, any number of classes can implement an interface.  • Also, one class can implement any number of interfaces. (Through this you can implement multiple 

inheritance). • To implement an interface, a class must create the complete set of methods defined by the interface.  • However, each class is free to determine the details of its own implementation. • Interfaces are designed to support dynamic method resolution at run time. 

 

Defining an Interface 

• An interface is defined much like a class. This is the general form of an interface:  access interface name { 

type  varname1 = value;   //work as final & static variable type varname2 = value; // ... type varnameN = value;  return‐type method‐name1(parameter‐list); return‐type method‐name2(parameter‐list); // ... return‐type method‐nameN(parameter‐list); 

}  

access   ‐    is either public or not used.  ‐ When no access specifier is included, then default access results, and the interface is only 

available to other members of the package in which it is declared.  ‐ When it is declared as public, the interface can be used by any other code. 

  name   ‐     is the name of the interface, and can be any valid identifier.  

methods in interfaces :  ‐ Methods which are declared have no bodies.  ‐ They end with a semicolon after the parameter list.  ‐ They are, essentially, abstract methods; there can be no default implementation of any method 

specified within an interface.  ‐ Each class that includes an interface must implement all of the methods.  

  variables in interfaces :  

‐ Variables can be declared inside of interface declarations.  ‐ They are implicitly final and static, meaning they cannot be changed by the implementing 

class.  ‐ They must also be initialized with a constant value.  

 

Page 28: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 28   

 

All methods and variables are implicitly public if the interface, itself, is declared as public.  Example for interface definition: 

 interface CallbackDemo  { 

void callback(int param); }  

Implementing Interfaces 

• Once an interface has been defined, one or more classes can implement that interface. • To implement an interface,  

o include the implements clause in a class definition, and o create the methods defined by the interface.  

• The general form of a class that  includes the implements clause looks like this:   access class classname [extends superclass] 

[implements interface [,interface...]] {  

// class‐body  

}  access  ‐ is either public or not used.   Note : 

If a class implements more than one interface, the interfaces are separated with a comma.   If a class implements two interfaces that declare the same method, then the same method will be used by 

clients of either interface.   The methods that implement an interface must be declared public.   Also, the type signature of the implementing method must match exactly the type signature specified in the 

interface definition. Example: 

interface CallbackDemo  { 

void callback(int param); } class Client implements CallbackDemo  { 

// Implement CallbackDemo's interface public void callback(int p)  { 

System.out.println("callback called with " + p); } 

} class TestIface1  { 

public static void main(String args[])  

Page 29: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 29   

 

{ Client  c = new Client(); c.callback(42); 

} } Output: 

  

It is both permissible and common for classes that implement interfaces to define additional members of their own.  

interface CallbackDemo  { 

void callback(int param); } class Client implements CallbackDemo { 

 // Implement Callback's interface public void callback(int p) { 

System.out.println("callback called with " + p); }  void nonIfaceMeth() { 

System.out.println("Classes that implement interfaces " + "may also define other members, too."); 

} } class TestIfaceDemo2  { 

public static void main(String args[]) { Client c = new Client(); c.callback(42); c.nonIfaceMeth();  

} } 

 

  

 

Page 30: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 30   

 

Variables in Interfaces 

You can use interfaces to import shared constants into multiple classes by simply declaring an interface that contains variables which are initialized to the desired values.  

When you implement that interface in a class, all of those variable names will be in scope as constants.   It is as if that class was importing the constant variables into the class name space as final variables.   They are implicitly final and static, meaning they cannot be changed by the implementing class.  

 import java.util.Random;  interface SharedConstants { 

 int NO = 0; int YES = 1; int MAYBE = 2; int LATER = 3; int SOON = 4; int NEVER = 5; 

 } class Question implements SharedConstants {  

Random rand = new Random(); int ask() { 

int prob = (int) (100 * rand.nextDouble()); if (prob < 30) return NO;     // 30% else if (prob < 60) return YES;     // 30% else if (prob < 75) return LATER;   // 15% else if (prob < 98) return SOON;   // 13% else return NEVER;   // 2% 

} } class AskMe implements SharedConstants { 

static void answer(int result) { switch(result) { 

case NO: System.out.println("No"); break; 

case YES: System.out.println("Yes"); break; 

case MAYBE: System.out.println("Maybe"); break; 

case LATER: 

Page 31: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 31   

 

System.out.println("Later"); break; 

case SOON: System.out.println("Soon"); break; 

case NEVER: System.out.println("Never"); break; 

} } public static void main(String args[]) { 

Question q = new Question(); answer(q.ask()); answer(q.ask()); answer(q.ask()); answer(q.ask()); 

} } Note that the results are different each time it is run. Output: 

  

Single Inheritance of Interfaces  ( Interfaces Can Be Extended ) 

One interface can inherit another by use of the keyword extends.   The syntax is the same as for inheriting classes.   When a class implements an interface that inherits another interface, it must provide implementations for 

all methods defined within the interface inheritance chain.  // One interface can extend another. interface A  { 

void meth1(); void meth2(); 

} // B now includes meth1() and meth2() ‐‐ it adds meth3(). interface B extends A  { 

void meth3(); }   

Page 32: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 32   

 

// This class must implement all of A and B class MyClass implements B { 

public void meth1()  { 

System.out.println("Implement meth1()."); } public void meth2()  { 

System.out.println("Implement meth2()."); } public void meth3()  { 

System.out.println("Implement meth3()."); } 

} class IFExtend  { 

public static void main(String arg[])  { 

MyClass ob = new MyClass(); ob.meth1(); ob.meth2(); ob.meth3(); 

} } Output: 

  

Accessing Implementations Through Interface References 

You can declare variables as object references that use an interface rather than a class type.   Any instance of any class that implements the declared interface can be referred to by such a variable.   The method to be executed is looked up dynamically at run time, allowing classes to be created later than 

the code which calls methods on them.   Example: 

interface CallbackDemo  { 

void callback(int param); } class Client implements CallbackDemo { 

// Implement Callback's interface 

Page 33: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 33   

 

public void callback(int p) { System.out.println("callback called with " + p); 

}  void nonIfaceMeth() { 

System.out.println("Classes that implement interfaces " + "may also define other members, too."); 

} } class TestIfaceDemo3  { 

public static void main(String args[])  { 

CallbackDemo c = new Client(); c.callback(42); c.nonIfaceMeth(); //Invalid 

} }  Output:  

    After applying comment……  

class TestIfaceDemo3  { 

public static void main(String args[])  { 

CallbackDemo c = new Client(); c.callback(42); //  c.nonIfaceMeth(); //Invalid 

} } 

    

Page 34: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 34   

 

Output:   

                 Note: 

variable c is declared to be of the interface type Callback, yet it was assigned an instance of Client.   Although c can be used to access the callback( ) method, it cannot access any other members of the Client 

class.   An interface reference variable only has knowledge of the methods declared by its interface declaration. 

// Another implementation of Callback. interface Callback  { 

void callback(int param); } class Client implements Callback { 

// Implement Callback's interface public void callback(int p) { 

System.out.println("callback called with " + p); } void nonIfaceMeth() { 

System.out.println("Classes that implement interfaces " + "may also define other members, too."); 

} } class AnotherClient implements Callback { 

// Implement Callback's interface public void callback(int p) { 

System.out.println("Another version of callback"); System.out.println("p squared is " + (p*p)); 

} } class TestIface2 { 

public static void main(String args[]) { Callback c = new Client(); AnotherClient ob = new AnotherClient(); c.callback(42); c = ob; // c now refers to AnotherClient object c.callback(42); 

} }   

Page 35: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 35   

 

Output: 

  Note: As you can see, the version of callback( ) that is called is determined by the type of object that c refers to at run time.   

Partial Implementations 

If a class includes an interface but does not fully implement the methods defined by that interface, then that class must be declared as abstract.  

For example:  interface CallbackDemo { 

void callback(int param); } 

abstract class Incomplete implements CallbackDemo { int a, b;  void show() { 

System.out.println(a + " " + b); } // ... 

} class A extends Incomplete { 

 void callback() { 

…………………..; …………………..; 

} // ... 

} Note:  Here, the class Incomplete does not implement callback( ) and must be declared as abstract. Any class that inherits Incomplete must implement callback( ) or be declared abstract itself. 

Page 36: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 36   

 

  Exercise : Write the output for the given program: 

 

  

Page 37: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 37   

 

2.11  Abstract classes    Vs    interfaces             

When should you use an abstract class, when an interface, when both? This table will help you decide.  

Interfaces vs Abstract Classes 

Feature  Interface Abstract class

Multiple inheritance 

A class may implement several interfaces. 

A class may extend only one abstract class. 

Default implementation 

An interface cannot provide any code at all, much less default code. 

An abstract class can provide complete code, default code, and/or just stubs that have to be overridden. 

Constants 

Static final constants only, can use them without qualification in classes that implement the interface.  

Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants. 

Third party convenience 

An interface implementation may be added to any existing third party class. 

A third party class must be rewritten to extend only from the abstract class. 

Is‐a vs able or can‐do 

Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects. 

An abstract class defines the core identity of its descendants. If you defined a Dog abstract class then Damamation descendants are Dogs, they are not merely dogable. Implemented interfaces enumerate the general things a class can do, not the things a class is. 

Plug‐in 

You can write a new replacement module for an interface that contains not one stick of code in common with the existing implementations. When you implement the interface, you start from scratch without any default implementation. You have to obtain your tools from other classes; nothing comes with the interface other than a few constants. This gives you freedom to implement a radically different internal design. 

You must use the abstract class as‐is for the code base, with all its attendant baggage, good or bad. The abstract class author has imposed structure on you. Depending on the cleverness of the author of the abstract class, this may be good or bad. Another issue that's important is what I call "heterogeneous vs. homogeneous." If implementors/subclasses are homogeneous, tend towards an abstract base class. If they are heterogeneous, use an interface. (Now all I have to do is come up with a good definition of hetero/homo‐geneous in this context.) If the various objects are all of‐a‐kind, and 

Page 38: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 38   

 

share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an interface. 

Homogeneity 

If all the various implementations share is the method signatures, then an interface works best. 

If the various implementations are all of a kind and share a common status and behavior, usually an abstract class works best. 

Maintenance If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it. 

Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it 

Speed 

Slow, requires extra indirection to find the corresponding method in the actual class. Modern JVMs are discovering ways to reduce this speed penalty. 

Fast

Terseness 

The constant declarations in an interface are all presumed public static final, so you may leave that part out. You can't call any methods to compute the initial values of your constants. You need not declare individual methods of an interface abstract. They are all presumed so. 

You can put shared code into an abstract class, where you cannot into an interface. If interfaces want to share code, you will have to write other bubblegum to arrange that. You may use methods to compute the initial values of your constants and variables, both instance and static. You must declare all the individual methods of an abstract class abstract. 

Adding functionality 

If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method. 

If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change. 

 

There are three main differences between an interface and an abstract class:  

• At the same time multiple interfaces can be implemented, but only extend one class • an abstract class may have some method implementation (non‐abstract methods, constructors, instance 

initializers and instance variables) and non‐public members • abstract classes may or may not be a little bit faster 

Page 39: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 39   

 

Main reason for the existence of interfaces in Java is: to support multiple inheritance. Languages supporting multiple implementation inheritance, an interface is equivalent to a fully abstract class (a class with only public abstract members). 

The above differentiation suggests when to use an abstract class and when to use an interface: 

• If you want to provide common implementation to subclasses then an abstract class is used, • If you want to declare non‐public members, the use abstract method • In case of abstract class, you are free to add new public methods in the future, • If you're confirm regarding the stablity of the API for the long run then use an interface • If you want to provide the implementing classes the opportunity to inherit from other sources at the same 

time then use an interface. 

In general, prefer interfaces if you don't need to use an abstract class, because they provide more design flexibility.  

When To Use Interfaces 

• An interface allows somebody to start from scratch to implement your interface or implement your interface in some other code whose original or primary purpose was quite different from your interface.  

• To them, your interface is only incidental, something that have to add on to the their code to be able to use your package.  

When To Use Abstract classes 

• An abstract class, in contrast, provides more structure. It usually defines some default implementations and provides some tools useful for a full implementation.  

• The catch is, code using it must use your class as the base. That may be highly inconvenient if the other programmers wanting to use your package have already developed their own class hierarchy independently. In Java, a class can inherit from only one base class.  

When to Use Both 

• You can offer the best of both worlds, an interface and an abstract class. Implementors can ignore your abstract class if they choose. The only drawback of doing that is calling methods via their interface name is slightly  their abstract class name.  

//Example: Interface interface CallbackDemo  { 

void callback(int param); } class Client implements CallbackDemo  { 

// Implement CallbackDemo's interface public void callback(int p)  { 

System.out.println("callback called with " + p); } 

Page 40: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 40   

 

class TestIface1  { 

public static void main(String args[])  { 

Client  c = new Client(); c.callback(42); 

} } Output: 

 //Example  : Abstract class 

// A Simple demonstration of abstract. abstract class A  { 

abstract void callme();  // concrete methods are still allowed in abstract classes void callmetoo()  { 

System.out.println("This is a concrete method."); } 

} class B extends A  { 

void callme()  { 

System.out.println("B's implementation of callme."); } 

} class AbstractDemo  { 

public static void main(String args[])  { 

A a = new A(); // Incorrect a.callme();     // Incorrect a.callmetoo();   // Incorrect  B b = new B(); b.callme(); b.callmetoo(); 

} } 

Page 41: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 41   

 

2.12  Package                   

• Defining package 

• Importing Packages 

• Use of static imports 

• Use of  CLASSPATH   for   class   loading 

• Access protection / Access Specifiers  Access specifiers for members of a package  Access specifiers for members of a class  Access specifiers for overriding methods 

Package • Packages are containers for classes that are used to keep the class name space compartmentalized.  • Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.  

 • For example, a package allows you to create a class named List, which you can store in your own 

package without concern that it will collide with some other class named List stored elsewhere.  

 

 Defining Package 

• To create a package is quite easy:  o Simply include a package command as the first statement in a Java source file.  o Any classes declared within that file will belong to the specified package.  

• This is the general form of the package statement: package pkgname; 

 ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ pkgname ‐  is the name of the package.  

Page 42: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 42   

 

For example, the following statement creates a package called MyPackage.  package MyPackage; 

 • The package statement defines a name space in which classes are stored.  • If you omit the package statement, the class names are put into the default package, which has no 

name.  • While the default package is fine for short  & sample programs, it is inadequate for real 

applications. Most of the time, you will define a package for your code.  • Java uses file system directories to store packages.  

For example,  the .class files for any classes you declare to be part of MyPackage  must be stored in a directory called MyPackage.  Remember that case is significant, and the directory name must match the package name exactly. 

• More than one file can include the same package statement.  • The package statement simply specifies to which package the classes defined in a file belong. It 

does not exclude other classes in other files from being part of that same package.  • You can create a hierarchy of packages. To do so, simply separate each package name from the 

one above it by use of a period.  • The general form of a multileveled package statement is shown here: 

 package pkg1[.pkg2[.pkg3]];  

A package hierarchy must be reflected in the file system of your Java development system.  For example, a package declared as package java.awt.image; needs to be stored in java\awt\image on your Windows file system. 

Be sure to choose your package names carefully. You cannot rename a package without renaming the directory in which the classes are stored. 

 

   

Page 43: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 43   

 

 

                     

          

                 

     

Page 44: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 44   

 

A Short Package Example // A simple package package MyPack;  class Balance { 

String name; double bal; Balance(String n, double b) { 

name = n; bal = b; 

} void show() { 

if(bal<0) System.out.print("‐‐> ");  

System.out.println(name + ": $" + bal); } 

} class AccountBalance { 

public static void main(String args[]) { Balance current[] = new Balance[3]; current[0] = new Balance("K. J. Fielding", 123.23); current[1] = new Balance("Will Tell", 157.02); current[2] = new Balance("Tom Jackson", ‐12.33); for(int i=0; i<3; i++)  

current[i].show(); } 

} Output: 

  

Save this file as AccountBalance.java in a directory called MyPack.  Next, compile the file. Make sure that the resulting     .class file      is also in the MyPack directory.   Then try executing the AccountBalance class, using the following command line: 

 java MyPack.AccountBalance  

• Remember, you will need to be in the directory above MyPack when you execute this command, or to have your CLASSPATH environmental variable set appropriately. 

Page 45: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 45   

 

Note:  AccountBalance is now part of the package MyPack. This means that it cannot be executed by itself. That is, you cannot use this command line:  

java AccountBalance AccountBalance must be qualified with its package name.  

Importing Packages • Java includes the import statement to bring certain classes, or entire packages, into visibility.  • Once imported, a class can be referred to directly, using only its name.  • The import statement is a convenience to the programmer and is not technically needed to write a 

complete Java program.  • If you are going to refer to a few dozen classes in your application, however, the import statement 

will save a lot of typing.  • In a Java source file, import statements occur immediately following the package statement (if it 

exists) and before any class definitions.  • This is the general form of the import statement: 

 import pkg1[.pkg2].(classname|*);  

pkg1  ‐    is the name of a top‐level package, and  pkg2  ‐    is the name of a subordinate package inside the outer package separated by a      dot (.).  

There is no practical limit on the depth of a package hierarchy, except that imposed by the file system.  

classname or a star (*) ‐ Finally, you specify either an explicit classname or a star (*),  which indicates that the Java compiler should import the entire  package or a single class.  Example: 

import java.io.*; import java.util.Date;  

• The star ( * ) form may increase compilation time—especially if you import several large packages. For this reason it is a good idea to explicitly name the classes that you want to use rather than importing whole packages.  

• However, the star ( * ) form has absolutely no effect on the run‐time performance or size of your classes.  Note: 

• All of the standard Java classes included with Java are stored in a package called java.  • The basic language functions are stored in a package inside of the java package called java.lang.  • Normally, you have to import every package or class that you want to use, but since Java is useless 

without much of the functionality in java.lang, it is implicitly imported by the compiler for all programs.  

• This is equivalent to the following line being at the top of all of your programs: import java.lang.*; 

Page 46: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 46   

 

Try at yourself:  Find the directory named : lang, io, util, awt   etc. to find  buit‐in packages location. 

Explore the following file and write about it whatever you find. C:\Program Files\Java\jdk1.6.0_11\src.zip 

 • If a class with the same name exists in two different packages that you import using the 

star form, the compiler will remain silent, unless you try to use one of the classes.  • In  that case, you will get a compile‐time error and have to explicitly name the class 

specifying its package.  • Any place you use a class name, you can use its fully qualified name, which includes its full 

package hierarchy.   Example:  import java.util.*;  class MyDate extends Date {   //…… }  The same example without the import statement looks like this:  class MyDate extends java.util.Date  {   //…… }  Example: balance.java 

package MyPack; /* Now, the Balance class, its constructor, and its show() method are public. This means that they can be used by non‐subclass code outside their package. */ public class Balance { 

String name; double bal; public Balance(String n, double b) { 

name = n; bal = b; 

} public void show() { 

if(bal<0) System.out.print("‐‐> "); System.out.println(name + ": $" + bal); 

Page 47: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 47   

 

}  TestBalance.java 

import MyPack.*;  class TestBalance { 

public static void main(String args[]) { /* Because Balance is public, you may use Balance class and call its constructor. */ Balance test = new Balance("S. Tendulkar", 99.88); test.show(); // you may also call show() 

} } 

 

  

OR  

         

Page 48: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 48   

 

static Import  

• A static import declaration (a new feature of J2SE 5.0) enables programmers to refer to imported static members as if they were declared in the class that uses them—the class name and a dot (.) are not required to use an imported static member.  

• A static import declaration has two forms— o imports a particular static member (which is known as single static import). The following 

syntax imports a particular static member:  Syntax: 

import static packageName.ClassName.staticMemberName; 

where,  

     packageName ‐ is the package of the class (e.g., java.lang),  

                   ClassName ‐ is the name of the class (e.g., Math) and  

     staticMemberName  ‐  is the name of the static field or method  

                                               (e.g., PI or abs).  

 

Example:  import static java.lang.Math.PI; 

 

o imports all static members of a class (which is known as static import on demand). The following syntax imports all static members of a class:

Syntax: import static packageName.ClassName.*;  where        packageName  ‐  is the package of the class (e.g., java.lang),       ClassName  ‐  is the name of the class (e.g., Math).        The asterisk (*)  ‐  indicates that all static members of the specified class should 

be                             available for use in the class(es) declared in the file.   

Example:  import static java.lang.Math.*;  

• Note : static import declarations import only static class members. Regular import statements should be used to specify the classes used in a program. 

 

 

 

Page 49: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 49   

 

Example  :  1 : Static import with Math methods. 

  //StaticImportTest.java     // Using static import to import static methods of class Math.     import static java.lang.Math.*;          public class StaticImportTest      {        public static void main( String args[] )         {           System.out.printf( "sqrt( 900.0 ) = %.1f\n", sqrt( 900.0 ) );           System.out.printf( "ceil( ‐9.8 ) = %.1f\n", ceil( ‐9.8 ) );           System.out.printf( "log( E ) = %.1f\n", log( E ) );           System.out.printf( "cos( 0.0 ) = %.1f\n", cos( 0.0 ) );        } // end main     } // end class StaticImportTest 

Output: sqrt( 900.0 ) = 30.0 ceil( ‐9.8 ) = ‐9.0 log( E ) = 1.0 cos( 0.0 ) = 1.0 

Example : 2 : Static import with Color class constants. import static java.awt.Color.*; public class ImportTest { public static void main(String args[]) { System.out.println(RED); } }

Finding Packages and CLASSPATH • As just explained, packages are mirrored by directories.  • This raises an important question:  

 How does the Java run‐time system know where to look for packages that you create?  

 Answer(1): 

By default, the Java run‐time system uses the current working directory as its starting point. Thus, if your package is in the current directory, or a subdirectory of the current directory, it will be found.  

Answer(2):  You can specify a directory path or paths by setting the CLASSPATH environmental variable.  

• For example, consider the following package specification. package MyPack; 

Page 50: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 50   

 

• In order for a program to find MyPack, one of two things must be true.  o Either the program is executed from a directory immediately above MyPack,  o or CLASSPATH must be set to include the path to MyPack.  

 • The first alternative is the easiest (and doesn’t require a change to CLASSPATH), but the second 

alternative lets your program find MyPack no matter what directory the program is in.  • The easiest way to try the examples shown in this book is to simply create the package directories 

below your current development directory, put the .class files into the appropriate directories and then execute the programs from the development directory.  

 CLASSPATH  ‐  an environment variable 

• CLASSPATH is an environment variable (User Variable) that determines where the JDK tools such as Java compiler and interpreter search for a .class file 

• It contains an ordered sequence of directories as well as .jar and .zip files.  (Note: Files with .jar and .zip suffixes are archives that can contain multiple  

 files ) • It is important to have the CLASSPATH variable set correctly when working with packages. • In command prompt you may set the value of an environment variable by typing a command such 

as the following:  set classpath=c:\project1;c:\project2   OR 

Set Environment Variable in Windows 

Right Click on My Computer ‐ > Properties 

 

Click on Environment Variable 

Page 51: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 51   

 

 

Click on New Button (in User  Variables portion) and set  Variable name : CLASSPATH Variable Value : C:\PROGS         

 or   any other path as desired Click “Ok” 

1. Let’s Test  Environment Variable Goto Start‐>Run>Cmd  

• You may confirm that CLASSPATH is set correctly by entering the command shown here: • Above  command displays the current setting of that environment variable. • JDK tools attempt to locate .class file as below: 

Current Directory     (if not found then) 

     Locations specified by CLASSPATH in a sequence  

• JDK tools search libraries automatically from the lib subdirectory where the JDK was  installed. 

 Exercise:    Assume that you created three packages named    a.b.c.d,    j.k.l.m,    and    r.s.t .    The .class files for these packages are stored in directories c:\lab8\a\b\c\d,      C:\freshman\chem101\j\k\l\m,     and       c:\seminar\r\s\t,   respectively.   How should CLASSPATH be set so the classes and interfaces in those three packages      can be located by the JDK tools ?  

Page 52: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 52   

 

Access Protection • Packages act as containers for classes and other subordinate packages.  • Classes act as containers for data and code. The class is Java’s smallest unit of abstraction.  • Because of the interplay between classes and packages, Java addresses five categories of visibility 

for class members: o Same Class o Subclasses in the same package o Non‐subclasses in the same package o Subclasses in different packages o Classes that are neither in the same package nor subclasses 

 

  

• While Java’s access control mechanism may seem complicated, we can simplify it as follows.  o Anything declared public can be accessed from anywhere.  o Anything declared private cannot be seen outside of its class.  o When a member does not have an explicit access specification, it is visible to subclasses as 

well as to other classes in the same package. This is the default access.  o If you want to allow an element to be seen outside your current package, but only to classes 

that subclass your class directly, then declare that element protected.  Example:  Remember that the classes for the two different packages need to be stored in directories named after their respective packages—in this case, p1 and p2.  

Page 53: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 53   

 

Protection.java    //Same class  package p1;  public class Protection { 

int n = 1; private int n_pri = 2; protected int n_pro = 3; public int n_pub = 4; public Protection() { 

System.out.println("base constructor"); System.out.println("n = " + n); System.out.println("n_pri = " + n_pri); System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); 

} }  

Derived.java   //Same package sub class  package p1; class Derived extends Protection { 

Derived() { System.out.println("derived constructor"); System.out.println("n = " + n); // class only // System.out.println("n_pri = " + n_pri); System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); 

} }  

SamePackage.java   //Same package non‐sub class  

package p1; class SamePackage { 

SamePackage() { Protection p = new Protection(); System.out.println("same package constructor"); System.out.println("n = " + p.n); // class only // System.out.println("n_pri = " + p.n_pri); System.out.println("n_pro = " + p.n_pro); System.out.println("n_pub = " + p.n_pub); 

} } 

Page 54: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 54   

 

Protection2.java:  //Different package sub class  package p2;  class Protection2 extends p1.Protection { 

Protection2() { System.out.println("derived other package constructor"); // class or package only // System.out.println("n = " + n); // class only // System.out.println("n_pri = " + n_pri); System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); 

} }  

OtherPackage.java:    //Different package non‐sub class  

package p2;  class OtherPackage { 

OtherPackage() { p1.Protection p = new p1.Protection(); System.out.println("other package constructor"); // class or package only // System.out.println("n = " + p.n); // class only // System.out.println("n_pri = " + p.n_pri); // class, subclass or package only // System.out.println("n_pro = " + p.n_pro); System.out.println("n_pub = " + p.n_pub); 

} } 

If you wish to try these two packages, here are two test files you can use.   

The test file for package p1 is shown below: Demo_for_p1.java // Demo package p1. package p1; // Instantiate the various classes in p1. public class Demo_for_p1 { 

public static void main(String args[]) { Protection ob1 = new Protection(); Derived ob2 = new Derived(); SamePackage ob3 = new SamePackage(); 

} } 

Page 55: FUNDAMENTALS OF JAVA PROGRAMMING - · PDF fileFUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit – 2 & 3.1 Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot)

 FUNDAMENTALS OF JAVA PROGRAMMING (JAVA)  Unit – 2 & 3.1    

 

Prepared By:‐ Paresh Tanna (MCA Dept, School of Engg., RK University – Rajkot) 55   

 

The test file for p2 is shown below: Demo_for_p2.java  

// Demo package p2.  package p2;  // Instantiate the various classes in p2. public class Demo_for_p2 { 

public static void main(String args[]) { Protection2 ob1 = new Protection2(); OtherPackage ob2 = new OtherPackage(); 

} } 

Instructions: 1) Save all files in relative folders. 2) Package name is case‐sensitive. So it must match with respective directory name. 3) Do as per following: 

      

• In general, a Java source file can contain any (or all) of the following four internal parts: o A single package statement (optional) o Any number of import statements (optional) o A single public class declaration (required) o Any number of classes private to the package (optional)