by Debasis Samanta
The basic element of object oriented Programming in Java is a class. Class is used to build an Application, to define an applet. A class defines the shape and behavior of an object. In Java, programmers are allowed to define their own classes or can borrow the class definition from outside (such as from built in classes, packages etc). In this Chapter, we will learn the theoretical notion of Object Oriented Programming : encapsulation, inheritance, and polymorphism. We will discuss how to create, extend, and instantiate our own classes. After the learning of this Chapter we will begin to utilize the real power of Java-oriented programming style.
A Class is a template for an object. Every object has a class which defines the structure of an object (that means what are various component in it, termed as member elements) its functional inter feces (called methods) which decide what messages the object will respond to and how. The general form of class definition is shown below.
Class Class Name [extends SuperClassName ] [ implements Interface ] { [declaration of member elements ] [ declaration of methods ] }
Those are included with [...] are optional. Member elements will be declared with usual convention as in C++ with the following syntax :
Methods are declared with the same convention of C ++ as :
[Modifier ] returnType MethodName (parameter list){ Statements (s) ; // Code for definition of the method. }
Putting the member elements and methods into together in the definition of a class called is called encapsulation. Following is a simple example to illustrate the defining a class.
Illustration 3.1 // Encapsulation // // A program that uses the circle class // Call this file Demonstration_31.java class Circle { double x,y; // The coordinates of the center double r; // The radius // Method that returns circumference double circumference(){ return 2*3.14159*r; } // Method that returns area double area(){ return (22/7)*r*r; } } //The following class declares an object of type Circle class Demonstration_31{ public static void main(String args[]){ Circle c = new Circle(); c.x = 0.0; c.y = 0.0; c.r = 5.0; System.out.println("Circumference" + c.circumference()); System.out.println("Area" + c.area()); } }
OUTPUT: |
Circumference31.4159 |
In the above Illustration 3.1, we have defined two classes namely Circle and Demonstration_31. Circle contains two member elements namely x and y and a method namely Circle( ). The class Demonstration_31 act as the main class which contains main( ). Note that how an object (instance of a class) can be created with new operator. This new operator creates a single instance of a named class and returns a reference to that object.
For example, P1, P3 and P4 are three reference to three instances of object Point. These three objects are instantiated by the getPoint() method. It also should be noted the multiple references to the same object , e.g. P1 and P2 are the two reference to point the same object; this means that any change to the object, the same object to which P1is referencing. Another important point to note in this regard is that, memory is allocated only when they are referred; when control reaches to P1 = null one reference of the same object is ceased to exist and at P2 =null , the memory allocated to it automatically freed. This automatic memory allocation and deallocation is due to automatic garbage collector in Java .
Illustration 3.2 // Encapsulation // // A program that declares two objects of the Circle class // Call this file CircleDemo2.java class Circle { double x, y; double r; double circumference(){ return 2*3.14159*r; } double area(){ return (22/7)*r*r; } } //The following class declares multiple objects of type Circle class Demonstration_32 { public static void main(String args[]){ Circle c1 = new Circle(); Circle c2 = new Circle(); // Initialize the circles c1.x = 3.0; c1.y = 4.0; c1.r = 5.0; c2.x = -4.0; c2.y = -8.0; c2.r = 10.0; System.out.println("Circumference Circle 1" + c1.circumference()); System.out.println("Area Circle 1" + c1.area()); System.out.println("Circumference Circle 2" + c2.circumference()); System.out.println("Area Circle 2" + c2.area()); } }
OUTPUT: |
Circumference Circle 131.4159 |
In the last example, we have used the method viz circle(..) to initialize an object.
Illustration 3.3 class Circle { double x,y; double r; double circumference(){ return 2*3.14159*r; } double area(){ return (22/7)*r*r; } } class Box{ double width; double height; double depth; double area(){ double a; a = (width*height + height*depth + width*depth) * 2; return a; } double volume(){ double v; v = width*height*depth; return v; } } // Declaring objects of type Circle and Box class Demonstration_33 { public static void main(String args[]){ Circle c = new Circle(); Box b = new Box(); // Initialize the circles c.x = 3.0; c.y = 4.0; c.r = 5.0; b.width = 3.0; b.height = 4.0; b.depth = 5.0; System.out.println("Circumference Circle" + c.circumference()); System.out.println("Area Circle" + c.area()); System.out.println("Area of Box" + b.area()); System.out.println("Volume of Box" + b.volume()); } }
OUTPUT: |
Circumference Circle31.4159 |
Illustration 3.4 // A program that uses simple Point class and naïve initialization of its data. class Point { int x; int y; } // This class declares an object of type Point. class Demonstration_34{ public static void main(String args[]) { Point mypoint = new Point(); // assign values to mypoint's instance variables mypoint.x = 10; mypoint.y = 20; // access the values from mypoint’s instance variable System.out.println("x " + mypoint.x); System.out.println("x " + mypoint.y); } }
OUTPUT: |
x 10 |
Illustration 3.5 /* Encapsulation: Defining a class with method */ class Point { int x,y; void setPoint( ) { x = 10; y = 10; } } // definition of another class. This is a main class class Demonstration_35 { float distance; public static void main (String args[ ]) { Point p = new Point( ); p.setPoint(); System.out.println ( " x = "+ p.x ); System.out.println ( " y = "+ p.y ); } }
OUTPUT: |
x = 10 |
Illustration 3.6 /* Automatic initialization in Java through the constructor as in C++*/ /* Encapsulation: Defining a class having method with parameter */ class Point { int x,y; void setPoint( int a, int b ) { x = a; y = b; } } // definition of another class. This is a main class class Demonstration_36 { float distance; public static void main (String args[ ]) { Point p1 = new Point( ); Point p2 = new Point( ); p1.setPoint(15, 20); p2.setPoint(0, 0); System.out.println ( " x = "+ p1.x ); System.out.println ( " y = "+ p1.y ); System.out.println ( " x = "+ p2.x ); System.out.println ( " y = "+ p2.y ); } }
OUTPUT: |
x = 15 |
Illustration 3.7 /* Encapsulation: Utilization of objects in a program */ class Point { int x,y; void getPoint(int a, int b) { x = a; y = b; } } // definition of another class. This is a main class class Demonstration_37 { static double distance; public static void main (String args[ ]) { Point p1 = new Point( ); Point p2 = p1; Point p3 = new Point ( ); Point p4 = new Point ( ); p1.getPoint (5, 10 ); p2.getPoint (15, 20); p3.getPoint (20, 30); p4.getPoint (30, 40); System.out.println (" X1 = " + p1.x + "Y1 = " + p1.y ); System.out.println ("X2=" + p2.x + "Y2 = " +p2.y ); int dx = p3.x - p4. x; // X2 - X1 int dy = p3.y - p4. y; // y2 - y1 distance = Math.sqrt (dx * dx + dy * dy );// (X2-X1)2 + (Y2-Y1)2 System.out.println ( " Distance = "+ distance ); } }
OUTPUT: |
X1 = 15 Y1 = 20 |
Illustration 3.8 //constructor// // A Java program to demonstrate working of constructor in Java class Circle { double x,y; double r; double circumference(){ return 2*3.14159*r; } double area(){ return (22/7)*r*r; } Circle(double a, double b, double c){ x = a; // Set center x-coordinate y = b; // Set center y-coordinate r = c; // Set radius } } class Demonstration_38{ public static void main(String arge[]){ Circle c1 = new Circle(3.0,4.0,5.0); Circle c2 = new Circle(-4.0,8.0,10.0); System.out.println("Circumference Circle 1" + c1.circumference()); System.out.println("Area Circle 1" + c1.area()); System.out.println("Circumference Circle 2" + c2.circumference()); System.out.println("Area Circle 2" + c2.area()); } }
OUTPUT: |
Circumference Circle 131.4159 |
Illustration 3.9 // Constructor // /* Demontration of constructor Overloading */ // Edit Demonstration_39.java class Circle { double x,y; double r; Circle(double a, double b, double c){ x = a; y = b; r = c; } Circle(double c){ x = 0; y = 0; r = c; } Circle(Circle c){ x = c.x; y = c.y; r = c.r; } Circle(){ x = 0.0; y = 0.0; r = 1.0; } double circumference(){ return 2*3.14159*r; } double area(){ return (22/7)*r*r; } } class Demonstration_39{ public static void main(String arge[]){ Circle c1 = new Circle(3.0,4.0,5.0); Circle c2 = new Circle(5.0); Circle c3 = new Circle(c1); Circle c4 = new Circle(); System.out.println("Circumference Circle 1" + c1.circumference()); System.out.println("Area Circle 1" + c1.area()); System.out.println("Circumference Circle 2" + c2.circumference()); System.out.println("Area Circle 2" + c2.area()); System.out.println("Circumference Circle 3" + c3.circumference()); System.out.println("Area Circle 3" + c3.area()); System.out.println("Circumference Circle 4" + c4.circumference()); System.out.println("Area Circle 4" + c4.area()); } }
OUTPUT: |
Circumference Circle 131.4159 |
Illustration 3.10 /*The following program shows the use of this() to avoid the name-space collision. */ //Edit Demonstration_310.java class Student{ int rollno; String name, course; float fee; Student(int rollno, String name, String course){ this.rollno = rollno; this.name = name; this.course = course; } Student(int rollno, String name, String course, float fee){ this(rollno,name,course);//reusing constructor this.fee=fee; } void display(){ System.out.println(rollno+" "+name+" "+course+" "+fee);} } class Demonstration_310{ public static void main(String args[]){ Student s1=new Student(111,"ankit","java"); Student s2=new Student(112,"sumit","java",6000f); s1.display(); s2.display(); } }
OUTPUT: |
111 ankit java 0.0 |
Illustration 3.11 /*Demontration of constructor Overloading */ // Edit Demonstration_311.java class Circle { double x,y; double r; Circle (double x, double y, double r){ this.x = x; this.y = y; this.r = r; } Circle (double r){ x = 0; y=0; this.r = r; } Circle (Circle c){ x = c.x; y = c.y; r = c.r; } Circle (){ x = 0.0; y = 0.0; r = 1.0; } double circumference(){ return 2*3.14159*r; } double area(){ return (22/7)*r*r; } } class Demonstration_311{ public static void main(String arge[]){ Circle c1 = new Circle(3.0,4.0,5.0); Circle c2 = new Circle(5.0); Circle c3 = new Circle(c1); Circle c4 = new Circle(); System.out.println("Circumference Circle 1" + c1.circumference()); System.out.println("Area Circle 1" + c1.area()); System.out.println("Circumference Circle 2" + c2.circumference()); System.out.println("Area Circle 2" + c2.area()); System.out.println("Circumference Circle 3" + c3.circumference()); System.out.println("Area Circle 3" + c3.area()); System.out.println("Circumference Circle 4" + c4.circumference()); System.out.println("Area Circle 4" + c4.area()); } }
OUTPUT: |
Circumference Circle 131.4159 |
Illustration 3.12 // Program to demonstrate use of this: to invoke current class method // Edit Demonstration_312.java class A{ void m(){System.out.println("hello m");} void n(){ System.out.println("hello n"); this.m(); } } class Demonstration_312{ public static void main(String args[]){ A a=new A(); a.n(); } }
OUTPUT: |
hello n |
Illustration 3.13 /* Special use of this keyword: No object creation to invoke method */ //Edit Demonstration_313.java class A{ A(){ this(5); System.out.println("hello a"); } A(int x){ System.out.println(x); } } class Demonstration_313{ public static void main(String args[]){ A a=new A(); } }
OUTPUT: |
5 |
Illustration 3.14 /* Demontration of constructor Overloading */ // Edit Demonstration_314.java class Circle { double x,y; double r; Circle (double x, double y, double r){ this.x = x; this.y = y; this.r = r; } Circle (double r){ this(0.0, 0.0, r); } Circle (Circle c){ this(c.x, c.y, c.r); } Circle (){ this(0.0, 0.0, 1.0); } double circumference(){ return 2*3.14159*r; } double area(){ return (22/7)*r*r; } } class Demonstration_314{ public static void main(String arge[]){ Circle c1 = new Circle(3.0,4.0,5.0); Circle c2 = new Circle(5.0); Circle c3 = new Circle(c1); Circle c4 = new Circle(); System.out.println("Circumference Circle 1" + c1.circumference()); System.out.println("Area Circle 1" + c1.area()); System.out.println("Circumference Circle 2" + c2.circumference()); System.out.println("Area Circle 2" + c2.area()); System.out.println("Circumference Circle 3" + c3.circumference()); System.out.println("Area Circle 3" + c3.area()); System.out.println("Circumference Circle 4" + c4.circumference()); System.out.println("Area Circle 4" + c4.area()); } }
OUTPUT: |
Circumference Circle 131.4159 |
When encapsulation is the first mechanism in Object Oriented Programming, the second fundamental Object Oriented mechanism is inheritance. This allows descendants of a class to inherit all of its member elements and methods from its ancestors as well as creates its own. These descendants are known as subclasses. A class’s immediate parent is called its super class. In Java, a special key word extends is used to implement this mechanism. Following is the example to illustrate this.
Illustration 3.15 // Example of Inheritance in Java // /* A simple example of inheritance. */ // Create a superclass. class A { int i, j; void showij() { System.out.println("i and j: " + i + " " + j); } } // Create a subclass by extending class A. class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i + j + k)); } } class Demonstration_61 { 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(); } }
OUTPUT: |
Contents of superOb: |
Illustration 3.16 /* Inheritance example: initializing through constructor */ class Box { double width; double height; double depth; Box(){ // Default setting by this constructor width = 0.0; height = 0.0; depth = 0.0; } Box(double w, double h, double d) { width = w; height = h; depth = d; } double volume() { // compute and return volume return width * height * depth; } } // Here, Box is extended to include weight. class BoxWeight extends Box { double weight; // weight of box // constructor for BoxWeight BoxWeight(double w, double h, double d, double m) { width = w; height = h; depth = d; weight = m; } } class Demonstration_62a { public static void main(String args[]) { Box mybox1 = new Box(); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); } }
OUTPUT: |
Volume of mybox1 is 0.0 |
Illustration 3.17 /* Inheritance example: initializing through constructor */ class Box { double width; double height; double depth; Box(){ // Default setting by this constructor width = 0.0; height = 0.0; depth = 0.0; } Box(double w, double h, double d) { width = w; height = h; depth = d; } double volume() { // compute and return volume return width * height * depth; } } // Here, Box is extended to include weight. class BoxWeight extends Box { double weight; // weight of box // Constructors for BoxWeight BoxWeight() { // Default constructor super(); // Call the default constructor in the super class weight = 0.0; } BoxWeight(double w, double h, double d, double m) { super(w, h, d); // Call the overloaded constructor in the super class weight = m; } } class Demonstration_62b { public static void main(String args[]) { Box mybox1 = new Box(10, 20, 15); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // System.out.println("Weight of mybox1 is " + mybox1.weight); ERROR! System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); } }
OUTPUT: |
Volume of mybox1 is 3000.0 |
Illustration 3.18 /* Example of a superclass variable referring to a subclass Object*/ class Box { double width; double height; double depth; Box() { // default constructor } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } double volume() { // compute and return volume return width * height * depth; } } // Here, Box is extended to include weight. class BoxWeight extends Box { double weight; // weight of box // constructor for BoxWeight BoxWeight(double w, double h, double d, double m) { width = w; height = h; depth = d; weight = m; } } class Demonstration_63 { public static void main(String args[]) { BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37); Box plainbox = new Box(); double vol; vol = weightbox.volume(); System.out.println("Volume of weightbox is " + vol); System.out.println("Weight of weightbox is " + weightbox.weight); System.out.println(); // assign BoxWeight reference to Box reference plainbox = weightbox; vol = plainbox.volume(); // OK, volume() defined in Box System.out.println("Volume of the box is " + vol); /* The following statement is invalid because plainbox does not define a weight member. */ // System.out.println("Weight of plainbox is " + plainbox.weight); } }
OUTPUT: |
Volume of weightbox is 105.0 |
Illustration 3.19 // Example of Inheritance in Java // /* Simple example of super concept */ // A complete implementation of BoxWeight. class Box { double width; double height; double depth; // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } } // BoxWeight now fully implements all constructors. class BoxWeight extends Box { double weight; // weight of box // constructor when all parameters are specified BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } } class Demonstration_64 { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); System.out.println(); } }
OUTPUT: |
Volume of mybox1 is 3000.0 |
Illustration 3.20 /* Example of super to overcome name hiding */ class A { int i; } // Create a subclass by extending class A. class B extends A { int i; // this i hides the i in A B(int a, int b) { super.i = a; // i in A i = b; // i in B } void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); } } class Demonstration_65 { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } }
OUTPUT: |
i in superclass: 1 |
Illustration 3.21 /* Code sharing through super concept */ class Cat { void speak() { System.out.println("Meaon ! "); } } class PetCat extends Cat { // PetCat is one type of Cat void speak() { System.out.println(" Meow ! "); } } class MagicCat extends Cat { // MagicCat is another kind of Cat static boolean noOne; void speak() { if (noOne) { super.speak(); // use the super class definition } else { System.out.println(" Hello World !"); } } } class Demonstration_66 { public static void main(String args[]) { PetCat c1 = new PetCat(); MagicCat c2 = new MagicCat(); c2.noOne = true; c2.speak(); c1.speak(); c2.noOne = false; c2.speak(); } }
OUTPUT: |
Meaon ! |
Illustration 3.22 /* Example of multilevel inheritance. */ // Start with Box. class Box { private double width; private double height; private double depth; // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } } // Add weight. class BoxWeight extends Box { double weight; // weight of box // constructor when all parameters are specified BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } } // Add shipping costs class Shipment extends BoxWeight { double cost; // constructor when all parameters are specified Shipment(double w, double h, double d, double m, double c) { super(w, h, d, m); // call superclass constructor cost = c; } } class Demonstration_67 { public static void main(String args[]) { Shipment shipment1 = new Shipment(10, 20, 15, 10, 3.41); Shipment shipment2 = new Shipment(2, 3, 4, 0.76, 1.28); double vol; vol = shipment1.volume(); System.out.println("Volume of shipment1 is " + vol); System.out.println("Weight of shipment1 is " + shipment1.weight); System.out.println("Shipping cost: $" + shipment1.cost); System.out.println(); vol = shipment2.volume(); System.out.println("Volume of shipment2 is " + vol); System.out.println("Weight of shipment2 is " + shipment2.weight); System.out.println("Shipping cost: $" + shipment2.cost); } }
OUTPUT: |
Volume of shipment1 is 3000.0 |
Illustration 3.23 /* A simple abstract class example */ abstract class Base { abstract void fun(); } class Derived extends Base { void fun() { System.out.println("Derived fun() is called"); } } class Demonstration_68 { public static void main(String args[]) { // Uncommenting the following line will cause compiler error as the // line tries to create an instance of abstract class. // Base b = new Base(); // We can have references of Base type. Base b = new Derived(); b.fun(); } }
OUTPUT: |
Derived fun() is called |
Illustration 3.24 // An abstract class with constructor abstract class Base { Base() { System.out.println("Base constructor is called"); } abstract void fun(); } class Derived extends Base { Derived() { System.out.println("Derived constructor is called"); } void fun() { System.out.println("Derived fun() is called"); } } class Demonstration_69{ public static void main(String args[]) { Derived d = new Derived(); d.fun(); } }
OUTPUT: |
Base constructor is called |
Illustration 3.25 // An abstract class without any abstract method abstract class Base { void fun() { System.out.println("Base fun() is called"); } } class Derived extends Base { Derived() { System.out.println("Derived constructor is called"); } void fun() { System.out.println("Derived fun() is called"); } } class Demonstration_610 { public static void main(String args[]) { Derived d = new Derived(); d.fun(); } }
OUTPUT: |
Derived constructor is called |
Illustration 3.26 // Final Class Inheritance – An Example final class Bike{} class Honda1 extends Bike{ void run(){ System.out.println("Running safely with 100kmph"); } } final class Demonstration_611 { public static void main(String args[]){ Honda1 honda = new Honda1(); honda.run(); } }
Illustration 3.27 // An abstract class without any abstract method abstract class Base { void fun() { System.out.println("Base fun() is called"); } } class Derived extends Base { Derived() { System.out.println("Derived constructor is called"); } void fun() { System.out.println("Derived fun() is called"); } } class Demonstration_610 { public static void main(String args[]) { Derived d = new Derived(); d.fun(); } }
OUTPUT: |
Final fun() is called |
Illustration 3.28 // An abstract class with a final method abstract class Base { final void fun() { System.out.println("Final fun() is called"); } } class Derived extends Base { Derived() { System.out.println("Derived constructor is called"); } void fun() { System.out.println("Derived fun() is called"); } } class Demonstration_612b { public static void main(String args[]) { Base b = new Derived(); b.fun(); } }
Another fundamental object oriented mechanism in Java is the polymorphism. Java allows polymorphism on methods. Polymorphism, meaning one object many shapes, is a simple concept that allows a method to have multiple implementations. This is also known as method overloading. Following is the Illustration 3.29 to illustrate the idea of polymorphism .
Illustration 3.29 // Polymorphism concept // class Point { int x,y; Point ( int x, int y ) { // It is a constructor this.x = x; this.y = y; } /*M1*/ float distance ( int x, int y) { // One definition of distance int dx = this.x - x; int dy = this.y - y; return (float) Math.sqrt ( dx* dx + dy * dy ); } /*M2*/ float distance (Point p) { // Overloaded definition of distance . return distance ( p.x, p.y) ; } } class Point3D extends Point { int z ; Point3D ( int x, int y, int z ) { // Constructor of Point3D super ( x, y ); this.z = z; } /*M3*/ float distance (int x,int y, int z ) { // Another definition of distance int dx = this.x - x; int dy = this.y - y; int dz = this.z - z ; return (float) Math.sqrt ( dx * dx + dy*dy + dz*dz ); } /*M4*/ float distance (Point3D pt) { return distance (pt.x, pt.y, pt.z ); } } class PointDistance { public static void main ( String args [ ] ) { Point p1 = new Point (10, 5) ; // 2-D point Point p3 = new Point3D (5, 10, 5); // 3-D point Point p2 = new Point (4, 1) ; // another 2-D point Point p4 = new Point3D ( 2,3,4 ); // another 3-D point float d0 = p1.distance ( 0,0); // M1 will be referred float d1 = p1.distance ( p2); // M2 will be referncd System.out.println ( "Distance from P2 to Origin = " + d0); System.out .println ( " Distance from P2 to P1 = " + d1) ; d1 = p4.distance (p3); // M4 will be referred System.out.println ( "Distance from P3 to P4= "+ d1); } }
OUTPUT: |
Distance from P2 to Origin = 11.18034 |
In the above example, we have seen, how the same method can be implemented in different ways. The concept of this type of method overloading is same as in C++. However, C++ allows the operator overloading too, Java does not.
Method can be called dynamically in Java. Whenever, a method is called on an object reference, the declared type of the object reference is checked at compile time to make sure that the method exists in the declared class. At run time, the object reference could be referring to an instance of some subclass of the declared reference type. This is illustrated in Illustration 3.30.
Illustration 3.30 // Method resolution during execution // class A { void callMe ( ) { System.out. println ( "I am from A ") ; } } class B extends A { void callMe ( ) { System.out.println ( "I am from B "); } } public class Who { public static void main(String args [ ] ) { A a = new B ( ) ; a.callMe ( ); } }
OUTPUT: |
I am from B |
In the above mentioned Illustration 3.30, we declared the variable to be of type A, then stored a reference to an object of class B in it. Now, when we call the methodcallMe( ) on a, the Java run time notices that the reference is actually an instance of B, so it calls B’ s callMe( ) method instead of A’s.
This form of dynamic run time resolution is one of the most powerful mechanisms that Object Oriented in Java brings to bear on code reuse and robustness. The ability for existing code libraries to call methods on instance of new classes without recompiling while maintaining a clean abstract interface is a profoundly powerful tool.
The mechanism by which one can control the use of objects, its member elements and methods is known as the access specification. This is done in Java by using three access modifier key words public, private , and protected.
Public : Member elements and methods can be marked as public and then they can be accessed from any other method in Java Programs. To indicate a method or element is public, precede it with the public key word .
The public modifier can be applied to classes as well as methods and variables. It then allows to make a class accessible to other classes in other Packages.
The public access specification is automatic, in the sense that, if no access specifier is mentioned then by default it is having public accessibility.
Private : Member elements and methods marked private can be used only marked private can be used only from inside their class. A private element / method is not visible in any other class, including subclasses . Also, a subclass cannot override a non-private method and make the new method private.
Protected : Member elements and methods marked protected can be used only from inside their class or in subclasses of that class. A subclass can still override a protected method or variable.
Note : It can be noted that the private and protected modifier can not be applied to classes.
Final: Apart of these, there is another access modifier known in Java which is known as final. All methods and member elements may be overridden by default. In Java, one can declare that methods or member elements cannot be allowed to override by subclasses. For those method and member elements final key word can be specified. Like member elements and methods, classes also can be declared final and a final class cannot be sub classed.
Abstract : Just as one can specify that a method can never be sub classed by marking it as final, one can indicate that a method must always be sub classed by using the abstract keyword in the method definition. When applied to a class, the abstract modifier indicates that the class has not been fully implemented and that it should not be instantiated. If applied to a member function declaration, the abstract modifier means that the function will be implemented in a subclass. Since the function has no implementation, the class cannot be instantiated, and must be declared as abstract .
Illustration 3.31 /* Example-1 of default access modifier */ //Save the following classes in the same file named as Demonstration_71.java class A { void msg(){System.out.println("Hi! I am in Class A"); } } class Demonstration_71 { public static void main(String args[]){ A obj = new A(); obj.msg(); } }
OUTPUT: |
Hi! I am in Class A |
Illustration 3.32 /* Example-2 of default access modifier */ //Save the following class as A.java class A { void msg(){System.out.println("Hi! I am in Class A"); } } //Save the following classes in the same file named as Demonstration_72.java class Demonstration_72 { public static void main(String args[]){ A obj = new A(); obj.msg(); } }
OUTPUT: |
Hi! I am in Class A |
Illustration 3.33 //Save this program as A.java in a sub-directory “pack1” /* Example-3 of default access modifier */ //Save the following class as A.java class A { void msg(){System.out.println("Hi! I am in Class A"); } } /* Save this program as Demonstration_73.java in another sub-directory “pack2” */ //Save the following class as Demonstration_73.java class Demonstration_73 { public static void main(String args[]){ A obj = new A(); obj.msg(); } }
OUTPUT: |
Hi! I am in Class A |
Illustration 3.34 /* Example-4 of default access modifier */ //Save this program as A.java in a sub-directory “pack1” package pack1; public class A { public void msg(){System.out.println("Hi! I am in Class A"); } } /* Save this program as Demonstration_74.java in another sub-directory “pack2” */ package pack2; import pack1.*; class Demonstration_74 { public static void main(String args[]){ A obj = new A(); //Compile Time Error obj.msg(); //Compile Time Error } } Note: Run the main class Demonstration_74 from pack2 …
Illustration 3.35 /* Example-5 of public access modifier */ class A{ public int data=40; public void msg(){ System.out.println("Class A: Hello Java!"); } } class Demonstration_75 { public static void main(String args[]){ A obj = new A(); //OK : Class A is public System.out.println(obj.data); //OK : data is public obj.msg(); //OK: msg is public } }
OUTPUT: |
40 |
Illustration 3.36 //Example-6 : Java program to illustrate public modifier package pack1; public class A1 { int data = 100; public void display() { System.out.println("NPTEL " + data); } } package pack2; import pack1.*; class Demonstration_76 { public static void main(String args[]) { A1 obj = new A1(); obj.display(); } }
Illustration 3.37 /* Example-1 : Private access modifier */ public class A{ private int data = 40; public void msg(){ System.out.println("Class A: Hello Java!"); } } public class Demonstration_77 { public static void main(String args[]){ A obj = new A(); //OK : Class A is public System.out.println(obj.data); //Compile Time Error : data is private obj.msg(); //OK : msg is public } }
Illustration 3.38 /* Example-2: Private access modifier */ class A{ private int data = 40; public void msg(){ System.out.println("Class A: Hello Java!" + data); } } public class Demonstration_78 { public static void main(String args[]){ //private int data2 = 100; //public int data2 = 100; int data2 = 100; A obj = new A(); //OK : Class A is public System.out.println("Class B:"+ data2); //OK: private data in the same class obj.msg(); // Private data is accessable through public method } }
OUTPUT: |
Class B:100 |
Illustration 3.39 /* Example-3: Private access modifier */ class A{ private A(){ //private constructor } void msg(){ System.out.println("Class A: Hello Java!"); } } public class Demonstration_79 { public static void main(String args[]){ A obj = new A(); //Compile Time Error } }
Illustration 3.40 /* Example 1: protected modifier */ //Save by A.java in a sub-directory pack1 package pack1; public class A { protected int rollNo = 555; protected void msg(){ System.out.println("Class A: Hello Java!" + rollNo); } } //Save by B.java in another sub-directory pack2 package pack2; import pack1.*; class Demonstration_710 { public static void main(String args[]){ A obj = new A(); obj.msg(); } }
OUTPUT: |
Class A: Hello Java!555 |
Illustration 3.41 /* Example 2: protected access specifier*/ //Save by A.java in a subdirectory pack1 package pack1; public class A{ protected int rollNo = 555; protected void msg(){ System.out.println("Class A: Hello Java!" +rollNo); } } //Save by B.java in another sub-directory pack2 package pack2; import pack1.*; class Demonstration_711 extends A{ public static void main(String args[]){ A obj = new A(); obj.msg(); System.out.println("Class B: Hello Java!" +obj.rollNo); } }
OUTPUT: |
Class A: Hello Java!555 |
Illustration 3.42 //Example-3: Java program to illustrate protected modifier package p1; //Class A public class A { protected void display() { System.out.println("NPTEL"); } } //Java program to illustrate protected modifier package p2; import p1.*; //importing all classes in package p1 //Class B is sub-class of A class Demonstration_712 extends A { public static void main(String args[]) { A obj = new A (); obj.display(); } }
OUTPUT: |
NPTEL |
Illustration 3.43 //Example-4: Java program to illustrate protected modifier package p1; //Class A protected class A // A class cannot be declared as protected…. { void display() { System.out.println("NPTEL"); } } //Java program to illustrate protected modifier package p2; import p1.*; //importing all classes in package p1 //Class B is sub-class of A class Demonstration_712 extends A { public static void main(String args[]) { A obj = new A(); obj.display(); } }
Illustration 3.44 /* Simple example of access modifier. In a class hierarchy, private members remain private to their class. This program contains an error and will not compile. */ // Create a superclass. class A { int i; // public by default private int j; // private to A void setij(int x, int y) { i = x; j = y; } } // A's j is not accessible here. class B extends A { int total; void sum() { total = i + j; // ERROR, j is not accessible here } } class Demonstration_714{ public static void main(String args[]) { B subOb = new B(); subOb.setij(10, 12); subOb.sum(); System.out.println("Total is " + subOb.total); } }
Illustration 3.45 /* Another example of access modifier with public, private and protected data */ class BaseClass { public int x = 10; private int y = 10; protected int z = 10; int a = 10; //Implicit Default Access Modifier public int getX() { return x; } public void setX(int x) { this.x = x; } private int getY() { return y; } private void setY(int y) { this.y = y; } protected int getZ() { return z; } protected void setZ(int z) { this.z = z; } int getA() { return a; } void setA(int a) { this.a = a; } } public class Demonstration_715 extends BaseClass { public static void main(String args[]) { BaseClass rr = new BaseClass(); rr.z = 0; Demonstration_715 subClassObj = new Demonstration_715(); //Access Modifiers - Public System.out.println("Value of x is : " + subClassObj.x); subClassObj.setX(20); System.out.println("Value of x is : " + subClassObj.x); //Access Modifiers - Public // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /* System.out.println("Value of y is : "+subClassObj.y); subClassObj.setY(20); System.out.println("Value of y is : "+subClassObj.y);*/ //Access Modifiers - Protected System.out.println("Value of z is : " + subClassObj.z); subClassObj.setZ(30); System.out.println("Value of z is : " + subClassObj.z); //Access Modifiers - Default System.out.println("Value of x is : " + subClassObj.a); subClassObj.setA(20); System.out.println("Value of x is : " + subClassObj.a); } }
OUTPUT: |
Value of x is : 10 |
Illustration 3.46 /* Example of method-overiding */ class A{ public void msg1() { System.out.println("Class A: Public!"); } private void msg2() { System.out.println("Class A: Private!"); } protected void msg3(){ System.out.println("Class A: Protected!"); } } public class Demonstration_716 extends A{ void msg(){ System.out.println("Class Main: Welcome!"); } public void msg1() { // If modifire is set to default it cannot overide. System.out.println("Overriding public method!"); } void msg2() { System.out.println("Overriding private method!"); } // If modifire is set to private it can be overidden. public void msg3(){ System.out.println("Overriding protected method!"); } public static void main(String args[]){ Demonstration_716 obj = new Demonstration_716(); obj.msg(); //obj.msg1(); //obj.msg2(); //obj.msg3(); } }
OUTPUT: |
Class Main: Welcome! |
In general, each instance of a class has its own copy of any member variables. However, it is possible to designate a member variable as belonging to the class itself independent of any object of that class. Such member variables are called static members and are declared with the static key word. These are often work as global variable about the instances of a class. Likewise, methods can also be declared as static. Such static methods then can be used outside of the context of any instances.
In order to initialize static variable, one may declare a static block which gets executed exactly once, when the class is first loaded. The following is a complete listing in order to understand static modifier.
Illustration 3.47 // Static extent of a variable or method // public class Demo{ public static void main(String args[]){ int b=0; System.out.println("Value of b = "+b); Student s1 = new Student(); s1.showData(); Student s2 = new Student(); s2.showData(); } } class Student { static int b; Student(){ //Constructor incrementing static variable b b++; } public static void showData(){ System.out.println("Value of b = "+b); } }
OUTPUT: |
Value of b = 0 |
From the foregoing discussion, it is evident that static is useful for creating methods which may be called directly by referring to name of the class in which they are declared. This is how Java implements global functions and global variables. This is why our main() should always be declared as static so that the classes contain the scope of the names to avoid collisions.
Illustration 3.48 /* while loop example */ public class Demonstration_51{ public static void main(String[] args){ int count = 1; System.out.println("Printing first 10 odd numbers"); while (count < 11) { System.out.print(" " +((2*count)-1)); count++; } } }
OUTPUT: |
Printing first 10 odd numbers |
Illustration 3.49 /* Do-While loop example */ public class Demonstration_52{ public static void main(String[] args){ int count = 1; System.out.println(" Printing first 10 even numbers"); do { System.out.print(" " + 2*count); count++; } while (count < 11); } }
OUTPUT: |
Printing first 10 even numbers |
Illustration 3.50 /* For loop example */ class Demonstration_53{ public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Count is: " + i); } } }
OUTPUT: |
Count is: 1 |
Illustration 3.51 /* Loop example with continue */ public class Demonstration_54{ public static void main(String args[]) { for(int i=0; i<10; i++) { System.out.print(i + " "); if (i%2 == 0) continue; System.out.println(" "); } } }
OUTPUT: |
0 1 |
Illustration 3.52 /* Loop example with break*/ class Demonstration_55{ public static void main(String args[]) { for(int i=1; ; i++) { if(i%10 ==0 ) break; // terminate loop if i is 10 System.out.println("i: " + i); } System.out.println("Loop complete."); } }
OUTPUT: |
i: 1 |
Illustration 3.53 /* Test for primes */ class Demonstration_56{ public static void main(String args[]) { int num; boolean isPrime = true; num = Integer.parseInt(args[0]); for(int i=2; i <= num/2; i++) { if((num % i) == 0) { isPrime = false; break; } } if(isPrime) System.out.println("Prime"); else System.out.println("Not Prime"); } }
Illustration 3.54 /* Menu selection using do-while and switch-case */ class Demonstration_57{ public static void main(String args[]) throws java.io.IOException { char choice; do { System.out.println("Help on:"); System.out.println(" 1. if"); System.out.println(" 2. switch"); System.out.println(" 3. while"); System.out.println(" 4. do-while"); System.out.println(" 5. for\n"); System.out.println("Choose one:"); choice = (char) System.in.read(); } while( choice < '1' || choice > '5'); System.out.println("\n"); switch(choice) { case '1': System.out.println("The if:\n"); System.out.println("if(condition) statement;"); System.out.println("else statement;"); break; case '2': System.out.println("The switch:\n"); System.out.println("switch(expression) {"); System.out.println(" case constant:"); System.out.println(" statement sequence"); System.out.println(" break;"); System.out.println(" // ..."); System.out.println("}"); break; case '3': System.out.println("The while:\n"); System.out.println("while(condition) statement;"); break; case '4': System.out.println("The do-while:\n"); System.out.println("do {"); System.out.println(" statement;"); System.out.println("} while (condition);"); break; case '5': System.out.println("The for:\n"); System.out.print("for(init; condition; iteration)"); System.out.println(" statement;"); break; } } }
Illustration 3.55 /* A variable declared inside pair of brackets “{” and “}” in a method has scope withing the brackets only.*/ public class Demonstration_58 { public static void main(String args[]) { { // The variable x has scope within // brackets int x = 10; System.out.println(x); } // Uncommenting below line would produce // error since variable x is out of scope. // System.out.println(x); } }
OUTPUT: |
10 |
Illustration 3.56 class Demonstration_59 { public static void main(String args[]) { for (int x = 0; x < 4; x++) { System.out.println(x); } // uncommenting Will produce error //System.out.println(x); } }
OUTPUT: |
0 |
Illustration 3.57 // Above program after correcting the error class Demonstration_510 { public static void main(String args[]) { int x; for (x = 0; x < 4; x++){ System.out.println(x); } System.out.println(x); } }
OUTPUT: |
0 |
Illustration 3.58 // Another example of scope of variable in a block… class Demonstration_511 { public static void main(String args[]) { int x; x = 10; if(x == 10) { int y = 20; System.out.println("x and y: " + x + " " + y); x = y * 2; } //y = 100; // Error: Out of scope System.out.println("x is " + x); } }
OUTPUT: |
x and y: 10 20 |
Illustration 3.59 // Example of static variable public class Circle{ static int circlecount = 0; // class variable public double x,y,r; // instance variables public Circle(double x, double y, double r){ this.x = x; this.y = y; this.r = r; } public Circle(double r){ this(0.0,0.0,r); circlecount++; } public Circle(Circle c){ this(c.x,c.y,c.r); circlecount++; } public Circle(){ this(0.0,0.0,0.1); circlecount++; } public double circumference(){ return (2*3.14159*r); } public double area(){ return(3.14159*r*r); } public static void main(String args[ ]){ Circle c1 = new Circle(); System.out.println("c1#"+ c1.circlecount); Circle c2 = new Circle(5.0); System.out.println("c2#"+ c2.circlecount); Circle c3 = new Circle(c1); System.out.println("c3#"+ c3.circlecount); System.out.println("c1#"+ c1.circlecount + " c2# " + c2.circlecount + " c3#"+ c3.circlecount); } }
OUTPUT: |
c1#1 |
Illustration 3.60 // Example of static method // A class method and instance method public class Circle{ public double x,y,r; static int circlecount=0; public Circle(double x, double y, double r){ this.x = x; this.y = y; this.r = r; //circlecount++; } public Circle(double r){ this(0.0,0.0,r); circlecount++; } public Circle(Circle c){ this(c.x,c.y,c.r); circlecount++; } public Circle(){ this(0.0,0.0,0.1); circlecount++; } // An instance method. Return the bigger of two circles. public Circle bigger(Circle c){ if(c.r>r) return c; else return this; } // A class method: Return the bigger of two classes. public static Circle bigger (Circle a, Circle b) { if (a.r > b.r) return a; else return b; } public static void main(String args[]){ Circle a = new Circle (2.0); Circle b = new Circle (3.0); Circle c = a.bigger (b); Circle d = Circle.bigger (a,b); } }
Illustration 3.61 // Example of factorial calculation public class RecursiveFactorial{ int n; int factorial(int n) { if (n == 0) return(1); else return(n*factorial(n-1)); } public static void main(String[] args) { RecursiveFactorial x = new RecursiveFactorial(); x.n = Integer.parseInt(args[0]); System.out.println("Factorial of "+ x.n + ": " + x.factorial(x.n)); } }
Illustration 3.62 // Example of Fibonacci sequence class RecursiveFibonacci { int n; int fibonacci(int n){ if (n == 0) return 0; else if (n == 1) return 1; else return(fibonacci(n-1) + fibonacci(n-2)); } public static void main(String args[]){ RecursiveFibonacci x = new RecursiveFibonacci(); x.n = Integer.parseInt(args[0]); for(int i = 0; i <= x.n; i++){ System.out.println(x.fibonacci(i)); } } }
Illustration 3.63 // Example of GCD Calculation public class RecursiveGCD { int m, n; int gcd(int m, int n){ if(m>n) return gcd(n,m); if(m==n)return m; if(m==0)return n; if(m==1)return 1; return gcd(m,n%m); } public static void main(String[] args) { RecursiveGCD g = new RecursiveGCD(); g.m = Integer.parseInt(args[0]); g.n = Integer.parseInt(args[1]); System.out.printf("GCD of %d and %d is %d.", g.m, g.n, g.gcd(g.m, g.n)); } }
Illustration 3.64 /* Example of recursion : Practic 1 */ class Demonstration_517{ static void myMethod( int counter){ if(counter == 0) return; else { System.out.println("Hello "+counter); myMethod(--counter); System.out.println(counter); return; } } public static void main(String args[]) { myMethod(10); // pass positive integer } }
OUTPUT: |
Hello 10 |
Illustration 3.65 /* Example of recursion : Practic 2 */ public class Demonstration_518{ static int count = 0; static void p(){ count++; if(count <= 5){ System.out.println("Hello " + count); p(); } } public static void main(String[] args) { p(); } }
OUTPUT: |
Hello 1 |
Practice 3.1 /* A program that uses simple Point class. Call this file PointDemo.java */ class Point { int x; int y; } // This class declares an object of type Point. class PointDemo { public static void main(String args[]) { Point mypoint = new Point(); // assign values to mypoint's instance variables mypoint.x = 10; mypoint.y = 20; // access the values from mypoint’s instance variable System.out.println("x " + mypoint.x); System.out.println("x " + mypoint.y); } } Is the compilation successful? What is the output?
Practice 3.2 /* Encapsulation: Defining a class with method */ class Point { int x,y; void setPoint ( ) { x = 10; y = 10; } } // definition of another class. This is a main class class PointDemo { float distance; public static void main (String args[ ] { Point p = new Point( ); p.setPoint(); System.out.println ( " x = "+ p.x ); System.out.println ( " y = "+ p.y ); } } Is the compilation successful? What is about the execution?
Practice 3.3 /* Encapsulation: Defining a class with method with parameter */ class Point { int x,y; void setPoint ( int a, int b, ) { x = a; y = b; } } // definition of another class. This is a main class class PointParameterDemo { float distance; public static void main (String args[ ] { Point p = new Point( ); p.setPoint(15, 20); System.out.println ( " x = "+ p.x ); System.out.println ( " y = "+ p.y ); } } (This problem has a minor mistake. Identify the mistake and then write the correct code.)
Practice 3.4 /* Encapsulation: declare more than one object of a class */ class Point { int x,y; void getPoint ( int a, int b ) { x = a; y = b; } } // definition of another class. This is a main class class PointsDemo { float distance; public static void main (String args[ ] { Point p1 = new Point( ); Point p2 = p1; Point p3 = new Point ( ); Point p4 = new Point ( ); p1.getPoint (5, 10 ); p2.getPoint (15, 20); p3.getPoint (20, 30); p4.getPoint (30, 40); System.out.println (" X1 = " + p1.x + "Y1 = " + p1.y ); System.out.printlin ("X2=" + p2.x + "Y2 = " +p2.y ); int dx = p3.x - p4. x; // X2 - X1 int dy = p3.y - p4. y; // y2 - y1 distance = Math.sqrt (dx * dx + dy * dy );// (X2-X1)2 + (Y2-Y1)2 System.out.println ( " Distance = "+ distance ); } } What is the output?
Practice 3.5 /* Example of constructors. (one default and one parameterized constructor) */ public class Cube { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube() { length = 10; breadth = 10; height = 10; } } Class DemoCube{ public static void main(String[] args) { Cube cubeObj; cubeObj = new Cube(); System.out.println("Volume of Cube is : " + cubeObj.getVolume()); } } What is the output?
Practice 3.6 /* Example of a cube class containing 2 constructors. (one default and one parameterized constructor) */ public class Cube1 { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube1() { length = 10; breadth = 10; height = 10; } Cube1(int l, int b, int h) { length = l; breadth = b; height = h; } } class Cube1Demo{ public static void main(String[] args) { Cube1 cubeObj1, cubeObj2; cubeObj1 = new Cube1(); cubeObj2 = new Cube1(10, 20, 30); System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume()); System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume()); } } What is the output?
Practice 3.7 /* Automatic initialization - concept of constructor */ class Point () { int x, y; Point () { x = 10 ; y = 5; } printPoint() { System.out.println("X = "+ this.x + " Y= " + this.y); } } class PointCreate1 { public static void main ( String args [ ] ) { Point p = new Point (); p.printPoint(); } } What is the output?
Practice 3.8 /* Automatic initialization - concept of constructor */ class Point () { int x, y; Point ( int x, int y ) { this.x = x ; this.y = y; } printPoint() { System.out.println("X = "+ this.x + " Y= " + this.y); } } class PointCreate2 { public static void main ( String args [ ] ) { Point p = new Point (10, 20 ); p.printPoint(); } } What is the output?
Practice 3.9 /* Automatic initialization – more than one constructor */ class Point () { int x, y; Point () { x = 30; y = 40; } Point ( int x, int y ) { this.x = x ; this.y = y; } printPoint() { System.out.println("X = "+ this.x + " Y= " + this.y); } } class PointCreate3 { public static void main ( String args [ ] ) { Point p1 = new Point (); Point p2 = new Point (10, 20 ); p1.printPoint(); p2.printPoint(); } } What is the output?
Practice 3.10 /* Passing objects as parameter */ class Test { int a,b; Test(int i, int j) { a = i; b = j; } boolean equals(Test o) { if((o.a == a) && (o.b == b)) return true; else return false; } } class PassObjectParameter { public static void main(String[] args) { Test ob1 = new Test(100,22); Test ob2 = new Test(100,22); Test ob3 = new Test(-1,-1); System.out.println("ob1 == ob2: " + ob1.equals(ob2)); System.out.println("ob1 <> ob3: " + ob1.equals(ob3)); } } What is the output?
Practice 3.11 /* Returning an object */ class Test { int a; Test(int i) { a = i; } Test incrByTen() { Test temp = new Test(a+10); return temp; } } class RetOb { public static void main(String args[]) { Test ob1 = new Test(2); Test ob2; ob2 = ob1.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase: " + ob2.a); } } What is the output?
Practice 3.12 /* Example of access modifier */ class BaseClass { public int x = 10; private int y = 10; protected int z = 10; int a = 10; //Implicit Default Access Modifier public int getX() { return x; } public void setX(int x) { this.x = x; } private int getY() { return y; } private void setY(int y) { this.y = y; } protected int getZ() { return z; } protected void setZ(int z) { this.z = z; } int getA() { return a; } void setA(int a) { this.a = a; } } public class SubclassInSamePackage extends BaseClass { public static void main(String args[]) { BaseClass rr = new BaseClass(); rr.z = 0; SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access Modifiers - Public System.out.println("Value of x is : " + subClassObj.x); subClassObj.setX(20); System.out.println("Value of x is : " + subClassObj.x); //Access Modifiers - Public // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /* System.out.println("Value of y is : "+subClassObj.y); subClassObj.setY(20); System.out.println("Value of y is : "+subClassObj.y);*/ //Access Modifiers - Protected System.out.println("Value of z is : " + subClassObj.z); subClassObj.setZ(30); System.out.println("Value of z is : " + subClassObj.z); //Access Modifiers - Default System.out.println("Value of x is : " + subClassObj.a); subClassObj.setA(20); System.out.println("Value of x is : " + subClassObj.a); } } what is the output?
Practice 3.13 /* The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output. */ class ArrayDemo { public static void main(String[] args) { int[] anArray; // declares an array of integers anArray = new int[10]; // allocates memory for 10 integers anArray[0] = 100; // initialize first element anArray[1] = 200; // initialize second element anArray[2] = 300; // etc. anArray[3] = 400; anArray[4] = 500; anArray[5] = 600; anArray[6] = 700; anArray[7] = 800; anArray[8] = 900; anArray[9] = 1000; System.out.println("Element at index 0: " + anArray[0]); System.out.println("Element at index 1: " + anArray[1]); System.out.println("Element at index 2: " + anArray[2]); System.out.println("Element at index 3: " + anArray[3]); System.out.println("Element at index 4: " + anArray[4]); System.out.println("Element at index 5: " + anArray[5]); System.out.println("Element at index 6: " + anArray[6]); System.out.println("Element at index 7: " + anArray[7]); System.out.println("Element at index 8: " + anArray[8]); System.out.println("Element at index 9: " + anArray[9]); } } what is the output?
Practice 3.14 /* Another array example */ class ArrayDemo { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; int i; for (i = 0; i < arrayOfInts.length; i++) { System.out.println("arrayOfInts[" + i + "] = " + arrayOfInts[i]); } } } what is the output?
Practice 3.15 /* Average an array of values */ class Average { public static void main(String args[]) { double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5}; double result = 0; int i; for(i=0; i<5; i++) result = result + nums[i]; System.out.println("Average is " + result / 5); } } what is the output?
Practice 3.16 /* Demonstrate a two-dimensional array */ class TwoDArray { public static void main(String args[]) { int twoD[][]= new int[4][5]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<5; j++) { twoD[i][j] = k; k++; } for(i=0; i<4; i++) { for(j=0; j<5; j++) System.out.print(twoD[i][j] + " "); System.out.println(); } } } what is the output?
Practice 3.17 /* Example of 2D Array: Manually allocate differing size second dimensions. */ class TestTwoDimArrays { static int [][] myArray = new int[3][]; // initialize # of rows public static void main(String[] args) { myArray[0] = new int[3]; // initialize # of cols myArray[1] = new int[4]; // in each row myArray[2] = new int[5]; for(int i=0; i<3; i++) // fill and print the array fillArray(i, i+3); System.out.println(); } private static void fillArray(int row, int col) { for( int i=0; iwhat is the output?
Practice 3.18 /* Example Multidimentional Array */ class MultiDimArrayDemo { public static void main(String[] args) { String[][] names = {{"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"}}; System.out.println(names[0][0] + names[1][0]); //Mr. Smith System.out.println(names[0][2] + names[1][1]); //Ms. Jones } } what is the output?
Practice 3.19 /* The following program, ArrayCopyDemo, declares an array of char elements, spelling the word "decaffeinated". It uses arraycopy to copy a subsequence of array components into a second array */ class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); } } what is the output?
Practice 3.20 /* Example ArrayList */ import java.util.*; class ArrayListDemo { public static void main(String args[]) { // create an array list ArrayList al = new ArrayList(); System.out.println("Initial size of al: " + al.size()); // add elements to the array list al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); // display the array list System.out.println("Contents of al: " + al); al.add(1, "A2"); System.out.println("Size of al after additions: " + al.size()); // display the array list System.out.println("Contents of al: " + al); System.out.println("Index of D : " + al.indexOf("D")); System.out.println("Value at 2: " + al.size()); System.out.println("The second elements is " + al.get(1)); // Remove element from the array list al.remove("F"); System.out.println("Size of al after deletions: " + al.size()); // display the array list System.out.println("Contents of al: " + al); // replacing an element at a particular index al.set(2,"G"); System.out.println("Size of al after deletions: " + al.size()); // display the array list System.out.println("Contents of al: " + al); // Remove element from the array list al.remove(2); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); // Remove all elements from the array list al.clear(); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); } } what is the output?
Practice 3.21 /* Example: convert an ArrayList into array */ import java.util.*; class ArrayListToArray { public static void main(String args[]) { // Create an array list ArrayList al = new ArrayList(); // Add elements to the array list al.add(new Integer(1)); al.add(new Integer(2)); al.add(new Integer(3)); al.add(new Integer(4)); System.out.println("Contents of al: " + al); // get array Object ia[] = al.toArray(); int sum = 0; // sum the array for(int i=0; iwhat is the output?
Practice 3.22 /* Example LinkList */ import java.util.*; public class LinkedListDemo{ public static void main(String[] args){ LinkedList link=new LinkedList(); link.add("a"); link.add("b"); link.add(new Integer(10)); System.out.println("The contents of array is" + link); System.out.println("The size of an linkedlist is" + link.size()); link.addFirst(new Integer(20)); System.out.println("The contents of array is" + link); System.out.println("The size of an linkedlist is" + link.size()); link.addLast("c"); System.out.println("The contents of array is" + link); System.out.println("The size of an linkedlist is" + link.size()); link.add(2,"j"); System.out.println("The contents of array is" + link); System.out.println("The size of an linkedlist is" + link.size()); link.add(1,"t"); System.out.println("The contents of array is" + link); System.out.println("The size of an linkedlist is" + link.size()); link.remove(3); System.out.println("The contents of array is" + link); System.out.println("The size of an linkedlist is" + link.size()); //access element using iterator Iterator iterator; //Create a iterator iterator = link.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); //Check list empty or not if (link.isEmpty()){ System.out.println("Linked list is empty"); } else{ System.out.println( "Linked list size: " + link.size()); } } } what is the output?
Practice 3.23 /* Example Vector */ //java.util.Vector and java.util.Enumeration; import java.util.*; public class VectorDemo{ public static void main(String[] args){ Vector< Object> vector = new Vector< Object>(); int primitiveType = 10; Integer wrapperType = new Integer(20); String str = "tapan joshi"; vector.add(primitiveType); vector.add(wrapperType); vector.add(str); vector.add(2, new Integer(30)); System.out.println("the elements of vector: " + vector); System.out.println("The size of vector are: " + vector.size()); System.out.println("The elements at position 2 is: " + vector.elementAt(2)); System.out.println("The first element of vector is: " + vector.firstElement()); System.out.println("The last element of vector is: " + vector.lastElement()); vector.removeElementAt(2); Enumeration e=vector.elements(); System.out.println("The elements of vector: " + vector); while(e.hasMoreElements()){ System.out.println("The elements are: " + e.nextElement()); } } } what is the output?
Practice 3.24 /* Example Stack class */ import java.util.*; public class StackDemo{ public static void main(String[] args) { Stack stack=new Stack(); stack.push(new Integer(10)); stack.push("a"); System.out.println("The contents of Stack is" + stack); System.out.println("The size of an Stack is" + stack.size()); System.out.println("The number poped out is" + stack.pop()); System.out.println("The number poped out is " + stack.pop()); //System.out.println("The number poped out is" + stack.pop()); System.out.println("The contents of stack is" + stack); System.out.println("The size of an stack is" + stack.size()); } } what is the output?
Practice 3.25 /* Implement Stack in Java */ import java.io.*; import java.util.*; public class StackImplement{ Stackstack; String str; int num, n; public static void main(String[] args){ StackImplement q = new StackImplement(); } public StackImplement(){ try{ stack = new Stack (); InputStreamReader ir = new InputStreamReader(System.in); BufferedReader bf = new BufferedReader(ir); System.out.print("Enter number of elements : "); str = bf.readLine(); num = Integer.parseInt(str); for(int i = 1; i <= num; i++){ System.out.print("Enter elements : "); str = bf.readLine(); n = Integer.parseInt(str); stack.push(n); } } catch(IOException e){} System.out.print("Retrieved elements from the stack : "); while (!stack.empty()){ System.out.print(stack.pop() + " "); } } } what is the output?
Practice 3.26 /* Example queue */ import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queueqe=new LinkedList (); qe.add("b"); qe.add("a"); qe.add("c"); qe.add("e"); qe.add("d"); // access queue using iterator Iterator it=qe.iterator(); System.out.println("Initial Size of Queue :"+qe.size()); while(it.hasNext()){ String iteratorValue=(String)it.next(); System.out.println("Queue Next Value :"+iteratorValue); } // get value and does not remove element from queue System.out.println("Queue peek :"+qe.peek()); // get first value and remove that object from queue System.out.println("Queue poll :"+qe.poll()); System.out.println("Final Size of Queue :"+qe.size()); } } what is the output?
Practice 3.27 /* Implement Queue in Java */ import java.io.*; import java.util.*; public class QueueImplement{ LinkedListlist; String str; int num; public static void main(String[] args){ QueueImplement q = new QueueImplement(); } public QueueImplement(){ try{ list = new LinkedList (); InputStreamReader ir = new InputStreamReader(System.in); BufferedReader bf = new BufferedReader(ir); System.out.println("Enter number of elements : "); str = bf.readLine(); if((num = Integer.parseInt(str)) == 0){ System.out.println("You have entered either zero/null."); System.exit(0); } else{ System.out.println("Enter elements : "); for(int i = 0; i < num; i++){ str = bf.readLine(); int n = Integer.parseInt(str); list.add(n); } } System.out.println("First element :" + list.removeFirst()); System.out.println("Last element :" + list.removeLast()); System.out.println("Rest elements in the list :"); while(!list.isEmpty()){ System.out.print(list.remove() + "\t"); } } catch(IOException e){ System.out.println(e.getMessage() + " is not a legal entry."); System.exit(0); } } } what is the output?
Practice 3.28 /* String operation example */ public class stringmethod{ public static void main(String[] args){ // Construct one String from another char c[] = {'J', 'a', 'v', 'a'}; String s1 = new String(c); String s2 = new String(s1); System.out.println(s1); System.out.println(s2); //calculate string length System.out.println(s2.length()); //use the case functions: System.out.println("toUpperCase: " + s1.toUpperCase()); System.out.println("toLowerCase: " + s1.toLowerCase()); //check for a certain character using indexOf() System.out.println("indexOf('s'): " + s1.indexOf('s')); System.out.println("indexOf('v'): " + s1.indexOf('v')); System.out.println("indexOf('av'): " + s1.indexOf("av")); //print out the beginning character using charAt() System.out.println("first character: " + s1.charAt(0)); // Construct string from subset of char array. byte ascii[] = {65, 66, 67, 68, 69, 70 }; String s3 = new String(ascii); System.out.println(s3); String s4 = new String(ascii, 2, 3); System.out.println(s4); //string concatination String age = "9"; String s = "He is " + age + " years old."; System.out.println(s); String string1 = "Hi"; String string2 = new String("Hello"); if (string1 == string2) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } String str = "Her name is Tamana and Tamana is a good girl."; String strreplace = "Sonia"; String result = str.replaceFirst("Tamana", strreplace); System.out.println(result); } } what is the output?
Practice 3.29 /* Simple version of bubble sort */ public class bubbleSort{ public static void main(String a[]){ int i; int array[] = {12,9,4,99,120,1,3,10}; System.out.println("Values Before the sort:\n"); for(i = 0; i < array.length; i++) System.out.print( array[i]+" "); System.out.println(); bubble_srt(array, array.length); System.out.print("Values after the sort:\n"); for(i = 0; ia[j]){ t = a[j-1]; a[j-1]=a[j]; a[j]=t; } } } } } what is the output?
Practice 3.30 /* Simple version of bidirectional bubble sort */ public class BidirectionalBubbleSort{ public static void main(String a[]){ int i; int array[] = {12,9,4,99,120,1,3,10}; System.out.println("Values Before the sort:\n"); for(i = 0; i < array.length; i++) System.out.print( array[i]+" "); System.out.println(); bidirectionalBubble_srt(array, array.length); System.out.print("Values after the sort:\n"); for(i = 0; iarray[j + 1]) { int T = array[j]; array[j] = array[j + 1]; array[j + 1] = T; } } for (j = n; --j >= st;) { if (array[j] > array[j + 1]) { int T = array[j]; array[j] = array[j + 1]; array[j + 1] = T; } } } } } what is the output?
Practice 3.31 /* Simple version of bidirectional insertion sort */ public class InsertionSort{ public static void main(String a[]){ int i; int array[] = {12,9,4,99,120,1,3,10}; System.out.print("Values Before the sort:\n"); for(i = 0; i < array.length; i++) System.out.print( array[i]+" "); System.out.println(); insertion_srt(array, array.length); System.out.print("Values after the sort:\n"); for(i = 0; i0) && (array[j-1] > B)){ array[j] = array[j-1]; j--; } array[j] = B; } } } what is the output?
Practice 3.32 /* Simple version of bidirectional merge sort */ public class mergeSort{ public static void main(String a[]){ int i; int array[] = {12,9,4,99,120,1,3,10}; System.out.print("Values Before the sort:\n"); for(i = 0; i < array.length; i++) System.out.print( array[i]+" "); System.out.println(); mergeSort_srt(array,0, array.length-1); System.out.print("Values after the sort:\n"); for(i = 0; i= high) { return; } int middle = (low + high) / 2; mergeSort_srt(array, low, middle); mergeSort_srt(array, middle + 1, high); int end_low = middle; int start_high = middle + 1; while ((lo <= end_low) && (start_high <= high)) { if (array[low] < array[start_high]) { low++; } else { int Temp = array[start_high]; for (int k = start_high- 1; k >= low; k--) { array[k+1] = array[k]; } array[low] = Temp; low++; end_low++; start_high++; } } } } what is the output?
Practice 3.33 /* Selection sort as a method of array */ class ArraySel { private double[] a;// ref to array a private int nElems; // number of data items public ArraySel(int max) // constructor { a = new double[max]; // create the array nElems = 0; // no items yet } public void insert(double value) // put element into array { a[nElems] = value; // insert it nElems++; // increment size } public void display() // displays array contents { for(int j=0;j< nElems; j++) // for each element System.out.print(a[j] + " "); // display it System.out.println(""); } public void selectionSort() { int out, in, min; for(out=0; out< nElems-1; out++) // outer loop { min = out; // minimum for(in=out+1; in< nElems; in++) // inner loop if(a[in] < a[min] ) // if min greater, min = in; // we have a new min swap(out, min); // swap them } // end for(outer) } // end selectionSort() private void swap(int one, int two) { double temp = a[one]; a[one] = a[two]; a[two] = temp; } } // end class ArraySel class SelectSortApp { public static void main(String[] args) { int maxSize = 100; // array size ArraySel arr; // reference to array arr = new ArraySel(maxSize); // create the array arr.insert(77); // insert 10 items arr.insert(99); arr.insert(44); arr.insert(55); arr.insert(22); arr.insert(88); arr.insert(11); arr.insert(00); arr.insert(66); arr.insert(33); arr.display(); // display items arr.selectionSort(); // selection-sort them arr.display(); // display them again } } what is the output?
Practice 3.34 /* Quick sort as method of array */ class ArrayIns { private double[] theArray; // ref to array theArray private int nElems; // number of data items public ArrayIns(int max) // constructor { theArray = new double[max]; // create the array nElems = 0; // no items yet } public void insert(double value) // put element into array { theArray[nElems] = value; // insert it nElems++; // increment size } public void display() // displays array contents { System.out.print("A="); for(int j=0; j0 && theArray[--rightPtr] > pivot); // (nop) if(leftPtr >= rightPtr) // if pointers cross, break; // partition done else // not crossed, so swap(leftPtr, rightPtr); // swap elements } // end while(true) swap(leftPtr, right); // restore pivot return leftPtr; // return pivot location } // end partitionIt() public void swap(int dex1, int dex2) // swap two elements { double temp = theArray[dex1]; // A into temp theArray[dex1] = theArray[dex2]; // B into A theArray[dex2] = temp; // temp into B } // end swap( } // end class ArrayIns class QuickSort1App { public static void main(String[] args) { int maxSize = 16; // array size ArrayIns arr; arr = new ArrayIns(maxSize); // create array for(int j=0; j< maxSize; j++) // fill array with { // random numbers double n = (int)(java.lang.Math.random()*99); arr.insert(n); } arr.display(); // display items arr.quickSort(); // quicksort them arr.display(); // display them again } // end main() } // end class QuickSort1App what is the output?
Practice 3.35 /* Sorting array of objects using insertion sort */ class Person { private String lastName; private String firstName; private int age; public Person(String last, String first, int a) { // constructor lastName = last; firstName = first; age = a; } public void displayPerson() { System.out.print(" Last name: " + lastName); System.out.print(", First name: " + firstName); System.out.println(", Age: " + age); } public String getLast() // get last name { return lastName; } } // end class Person class ArrayInOb { private Person[] a; // ref to array a private int nElems; // number of data items public ArrayInOb(int max) // constructor { a = new Person[max]; // create the array nElems = 0; // no items yet } // put person into array public void insert(String last, String first, int age) { a[nElems] = new Person(last, first, age); nElems++; // increment size } public void display() // displays array contents { for(int j=0; j0 && a[in-1].getLast().compareTo(temp.getLast())>0) // until smaller one found, { a[in] = a[in-1]; // shift item to the right --in; // go left one position } a[in] = temp; // insert marked item } // end for } // end insertionSort() } // end class ArrayInOb //////////////////////////////////////////////////////////////// class ObjectSortApp { public static void main(String[] args) { int maxSize = 100; // array size ArrayInOb arr; // reference to array arr = new ArrayInOb(maxSize); // create the array arr.insert("Evans", "Patty", 24); arr.insert("Smith", "Doc", 59); arr.insert("Smith", "Lorraine", 37); arr.insert("Smith", "Paul", 37); arr.insert("Yee", "Tom", 43); arr.insert("Hashimoto", "Sato", 21); arr.insert("Stimson", "Henry", 29); arr.insert("Velasquez", "Jose", 72); arr.insert("Vang", "Minh", 22); arr.insert("Creswell", "Lucinda", 18); System.out.println("Before sorting:"); arr.display(); // display items arr.insertionSort(); // insertion-sort them System.out.println("After sorting:"); arr.display(); // display them again } // end main() } // end class ObjectSortApp what is the output?
Practice 3.36 /* This example shows how to sort elements of Java ArrayList in descending order using comparator and reverseOrder method of Collections class. */ import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class SortArrayListInDescendingOrderExample { public static void main(String[] args) { //create an ArrayList object ArrayList arrayList = new ArrayList(); //Add elements to Arraylist arrayList.add("A"); arrayList.add("B"); arrayList.add("C"); arrayList.add("D"); arrayList.add("E"); /* To get comparator that imposes reverse order on a Collection use static Comparator reverseOrder() method of Collections class */ Comparator comparator = Collections.reverseOrder(); System.out.println("Before sorting ArrayList in descending order : " + arrayList); /* To sort an ArrayList using comparator use, static void sort(List list, Comparator c) method of Collections class. */ Collections.sort(arrayList,comparator); System.out.println("After sorting ArrayList in descending order : " + arrayList); } } what is the output?
Practice 3.37 /* Example of binary search in sorted array */ public class BinarySearch { public static final int NOT_FOUND = -1; public static int binarySearch( Comparable [ ] a, Comparable x ) { int low = 0; int high = a.length - 1; int mid; while( low <= high ) { mid = ( low + high ) / 2; if( a[ mid ].compareTo( x ) < 0 ) low = mid + 1; else if( a[ mid ].compareTo( x ) > 0 ) high = mid - 1; else return mid; } return NOT_FOUND; // NOT_FOUND = -1 } // Test program public static void main( String [ ] args ) { int SIZE = 8; Comparable [ ] a = new Integer [ SIZE ]; for( int i = 0; i < SIZE; i++ ) a[ i ] = new Integer( i * 2 ); for( int i = 0; i < SIZE * 2; i++ ) System.out.println( "Found " + i + " at " +binarySearch( a, new Integer( i ) ) ); } } what is the output?
Practice 3.38 /* Binary search in ArrayList */ /* Perform Binary Search on Java ArrayList Example This java example shows how to search an element of Java ArrayList using binarySearch method of Collections class. binarySearch method uses binary search algorithm to search an element. */ import java.util.ArrayList; import java.util.Collections; public class BinarySearchArrayListExample { public static void main(String[] args) { //create an ArrayList object ArrayList arrayList = new ArrayList(); //Add elements to Arraylist arrayList.add("1"); arrayList.add("4"); arrayList.add("2"); arrayList.add("5"); arrayList.add("3"); /* To Search an element of Java ArrayList using binary search algorithm use,static int binarySearch(List list, Object element) method of Collections class.This method returns the index of the value to be searched, if found in the ArrayList. Otherwise it returns (- (X) - 1) where X is the index where the the search value would be inserted. i.e. index of first element that is grater than the search value or ArrayList.size(), if all elements of an ArrayList are less than the search value. Please note that the ArrayList MUST BE SORTED before it can be searchedusing binarySearch method. */ //First sort an ArrayList using sort method of Collections class Collections.sort(arrayList); System.out.println("Sorted ArrayList contains : " + arrayList); //search an element using binarySearch method of Collections class int index = Collections.binarySearch(arrayList,"4"); System.out.println("Element found at : " + index); } } what is the output?
Practice 3.39 /* Example of Binary Search Tree */ class Node { private int key; private Node parent; private Node leftChild; private Node rightChild; public Node(int key, Node leftChild, Node rightChild) { this.setKey(key); this.setLeftChild(leftChild); this.setRightChild(rightChild); } public void setKey(int key) { this.key = key; } public int getKey() { return key; } public void setParent(Node parent) { this.parent = parent; } public Node getParent() { return parent; } public void setLeftChild(Node leftChild) { this.leftChild = leftChild; } public Node getLeftChild() { return leftChild; } public void setRightChild(Node rightChild) { this.rightChild = rightChild; } public Node getRightChild() { return rightChild; } } class BinarySearchTree { private Node root; public void insert(int key) { insert(new Node(key, null, null)); } public void insert(Node z) { Node y = null; Node x = root; while (x != null) { y = x; if (z.getKey() < x.getKey()) { x = x.getLeftChild(); } else { x = x.getRightChild(); } } z.setParent(y); if (y == null){ root = z; } else if (z.getKey() < y.getKey()) { y.setLeftChild(z); } else { y.setRightChild(z); } } public void preorderTraversal() { preorderTraversal(root); } public void preorderTraversal(Node node) { if (node != null) { System.out.print(node.getKey() + " "); preorderTraversal(node.getLeftChild()); preorderTraversal(node.getRightChild()); } } public void inorderTraversal() { inorderTraversal(root); } private void inorderTraversal(Node node) { if (node != null) { inorderTraversal(node.getLeftChild()); System.out.print(node.getKey() + " "); inorderTraversal(node.getRightChild()); } } public void postorderTraversal() { postorderTraversal(root); } private void postorderTraversal(Node node) { if (node != null) { postorderTraversal(node.getLeftChild()); postorderTraversal(node.getRightChild()); System.out.print(node.getKey() + " "); } } } class BinarySearchTreeTest { public static void main(String[] args) { BinarySearchTree bst = new BinarySearchTree(); int[] input = new int[] { 8, 3, 10, 1, 6, 14, 4, 7, 13 }; for (int i : input) { bst.insert(i); } System.out.println("Preorder Traversal:"); bst.preorderTraversal(); System.out.println( "\nInorder Traversal:"); bst.inorderTraversal(); System.out.println("\nPostorder Traversal:"); bst.postorderTraversal(); } } what is the output?
Practice 3.40 /* Method overloading. */ class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a * a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } } what is the output?
Practice 3.41 /* Constructor overloading */ public class Cube { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube() { this(10, 10); System.out.println("Initialized with Default Constructor"); } Cube(int l, int b) { this(l, b, 10); System.out.println("Initialized with Constructor having 2 params"); } Cube(int l, int b, int h) { length = l; breadth = b; height = h; System.out.println("Initialized with Constructor having 3 params"); } Cube(Cube ob) { //pass object to constructor length = ob.length; breadth = ob.breadth; height = ob.height; System.out.println("Finished with Constructor having object params"); } public static void main(String[] args) { Cube cubeObj1, cubeObj2, cubeObj3; cubeObj1 = new Cube(); cubeObj2 = new Cube(10, 20, 30); cubeObj3 = new Cube(cubeObj2); // Creating clone object System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume()); System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume()); System.out.println("Volume of Cube3 is : " + cubeObj3.getVolume()); } } what is the output?
Practice 3.42 /* A simple example of inheritance. */ // Create a superclass. class A { int i, j; void showij() { System.out.println("i and j: " + i + " " + j); } } // Create a subclass by extending class A. class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i + j + k)); } } class SimpleInheritance { public static void main(String args[]) { A superOb = new A(); B subOb = new B(); // The superclass may be used by itself. superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println(); /* The subclass has access to all public members of its superclass. */ subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); } } what is the output?
Practice 3.43 /* Inheritance example: initializing through constructor */ class Box { double width; double height; double depth; Box(){ // constructor used when all dimensions specified } Box(double w, double h, double d) { width = w; height = h; depth = d; } double volume() { // compute and return volume return width * height * depth; } } // Here, Box is extended to include weight. class BoxWeight extends Box { double weight; // weight of box // constructor for BoxWeight BoxWeight(double w, double h, double d, double m) { width = w; height = h; depth = d; weight = m; } } class DemoBoxWeight { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); } } what is the output?
Practice 3.44 /* Inheritance example: initializing through constructor */ class Box { double width; double height; double depth; Box(){ // constructor used when all dimensions specified } Box(double w, double h, double d) { width = w; height = h; depth = d; } double volume() { // compute and return volume return width * height * depth; } } // Here, Box is extended to include weight. class BoxWeight extends Box { double weight; // weight of box // constructor for BoxWeight BoxWeight(double w, double h, double d, double m) { width = w; height = h; depth = d; weight = m; } } class DemoBoxWeight { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); } } what is the output?
Practice 3.45 /* Example of a superclass variable referring to a subclass Object*/ class Box { double width; double height; double depth; Box() { // default constructor } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } double volume() { // compute and return volume return width * height * depth; } } // Here, Box is extended to include weight. class BoxWeight extends Box { double weight; // weight of box // constructor for BoxWeight BoxWeight(double w, double h, double d, double m) { width = w; height = h; depth = d; weight = m; } } class RefDemo { public static void main(String args[]) { BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37); Box plainbox = new Box(); double vol; vol = weightbox.volume(); System.out.println("Volume of weightbox is " + vol); System.out.println("Weight of weightbox is " + weightbox.weight); System.out.println(); // assign BoxWeight reference to Box reference plainbox = weightbox; vol = plainbox.volume(); // OK, volume() defined in Box System.out.println("Volume of plainbox is " + vol); /* The following statement is invalid because plainbox does not define a weight member. */ // System.out.println("Weight of plainbox is " + plainbox.weight); } } what is the output?
Practice 3.46 /* Simple example of access modifier. In a class hierarchy, private members remain private to their class. This program contains an error and will not compile. */ // Create a superclass. class A { int i; // public by default private int j; // private to A void setij(int x, int y) { i = x; j = y; } } // A's j is not accessible here. class B extends A { int total; void sum() { total = i + j; // ERROR, j is not accessible here } } class Access { public static void main(String args[]) { B subOb = new B(); subOb.setij(10, 12); subOb.sum(); System.out.println("Total is " + subOb.total); } } what is the output?
Practice 3.47 /* Another example of access modifier with public, private and protected data */ class BaseClass { public int x = 10; private int y = 10; protected int z = 10; int a = 10; //Implicit Default Access Modifier public int getX() { return x; } public void setX(int x) { this.x = x; } private int getY() { return y; } private void setY(int y) { this.y = y; } protected int getZ() { return z; } protected void setZ(int z) { this.z = z; } int getA() { return a; } void setA(int a) { this.a = a; } } public class SubclassInSamePackage extends BaseClass { public static void main(String args[]) { BaseClass rr = new BaseClass(); rr.z = 0; SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access Modifiers - Public System.out.println("Value of x is : " + subClassObj.x); subClassObj.setX(20); System.out.println("Value of x is : " + subClassObj.x); //Access Modifiers - Public // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /* System.out.println("Value of y is : "+subClassObj.y); subClassObj.setY(20); System.out.println("Value of y is : "+subClassObj.y);*/ //Access Modifiers - Protected System.out.println("Value of z is : " + subClassObj.z); subClassObj.setZ(30); System.out.println("Value of z is : " + subClassObj.z); //Access Modifiers - Default System.out.println("Value of x is : " + subClassObj.a); subClassObj.setA(20); System.out.println("Value of x is : " + subClassObj.a); } } what is the output?
Practice 3.48 /* Sinple example of super concept */ // A complete implementation of BoxWeight. class Box { private double width; private double height; private double depth; // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } } // BoxWeight now fully implements all constructors. class BoxWeight extends Box { double weight; // weight of box // constructor when all parameters are specified BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } } class DemoSuper { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); System.out.println(); } } what is the output?
Practice 3.49 /* Example of super to overcome name hiding */ class A { int i; } // Create a subclass by extending class A. class B extends A { int i; // this i hides the i in A B(int a, int b) { super.i = a; // i in A i = b; // i in B } void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); } } class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } } what is the output?
Practice 3.50 /* Code sharing through super concept */ class Cat { void speak() { System.out.println("Meaon ! "); } } class PetCat extends Cat { // PetCat is one type of Cat void speak() { System.out.println(" Meow ! "); } } class MagicCat extends Cat { // MagicCat is another kind of Cat static boolean noOne; void speak() { if (noOne) { super.speak(); // use the super class definition } else { System.out.println(" Hello World !"); } } } class ManyCats { public static void main(String args[]) { PetCat c1 = new PetCat(); MagicCat c2 = new MagicCat(); c2.noOne = true; c2.speak(); c1.speak(); c2.noOne = false; c2.speak(); } } what is the output?
Practice 3.51 /* Example of multilevel inheritance. */ // Start with Box. class Box { private double width; private double height; private double depth; // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } } // Add weight. class BoxWeight extends Box { double weight; // weight of box // constructor when all parameters are specified BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } } // Add shipping costs class Shipment extends BoxWeight { double cost; // constructor when all parameters are specified Shipment(double w, double h, double d, double m, double c) { super(w, h, d, m); // call superclass constructor cost = c; } } class DemoShipment { public static void main(String args[]) { Shipment shipment1 = new Shipment(10, 20, 15, 10, 3.41); Shipment shipment2 = new Shipment(2, 3, 4, 0.76, 1.28); double vol; vol = shipment1.volume(); System.out.println("Volume of shipment1 is " + vol); System.out.println("Weight of shipment1 is " + shipment1.weight); System.out.println("Shipping cost: $" + shipment1.cost); System.out.println(); vol = shipment2.volume(); System.out.println("Volume of shipment2 is " + vol); System.out.println("Weight of shipment2 is " + shipment2.weight); System.out.println("Shipping cost: $" + shipment2.cost); } } what is the output?
Practice 3.52 /* Polymorphism and Overriding concept */ //base class class Base { int i=1; int j=2; public Base(){ } public void display(){ System.out.println("i="+i); System.out.println("i="+j); } } //derived class class Derived extends Base{ int p=3; int q=4; public Derived(){ } public void display(){ System.out.println("p="+p); System.out.println("q="+q); } public void uniqueDisplay(){ System.out.println(" This display is unique to Derived"); } } public class AccessCheck{ public static void main(String[] args){ Base b=new Base(); Derived d=new Derived(); b.display(); d.display(); d.uniqueDisplay(); // derived is assigned to base b=d; // Object is derived, reference is of base type b.display(); //b.uniqueDisplay(); // Uncomment this line, and check } } what is the output?
Practice 3.53 /* Using run-time polymorphism. */ class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } double area() { System.out.println("Area for Figure is undefined."); return 0; } } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } class FindAreas { public static void main(String args[]) { Figure f = new Figure(10, 10); Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; figref = r; System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); figref = f; System.out.println("Area is " + figref.area()); } } what is the output?
Read at most 10 names of students and store them into an array of String nameOfStudents[10]. Sort the names into the lexicographic order. Display the sorted list of names. | |
Define a class Complex to represent an object for a complex number like Z = X + i.Y with the following methods:
Write the main class and instantiate the objects of the above mentioned classes.Complex add(Complex z1, Complex z2) //To add two complex numbers Complex sub(Complex z1, Complex z2) //To subtract two complex numbers Complex mul(Complex z1, Complex z2) // To multiply two complex numbers float magnitude(Complex z) // To find the modulus Complex conjugate(Complex z) // To find the complex conjugate | |
Add the necessary methods in the class PointCreate3 (Practice 3.8) to calculate the area and perimeter of a rectangle given the two corner coordinates. | |
Read at most 10 names of students and store them into an array of String nameOfStudents[10]. Sort the names into the lexicographic order. Display the sorted list of names. | |
Define a class Employee with usual member for an employee like empCode(String), empName(String), dateOfBirth(Date), dateOfJoin(Date), designationCode(int), salary(float).Create a list to store data about 10 employees using Vector. Manipulate the list using the methods in class Vector. | |
Define an one dimensional array "vivid" of type float. Read the values from the keyboard to load the array. Calcualte and then print the average of all the values in "vivid".. | |
Define two 2D arrays of integers, namely A[3]4] and B[4][2]. Store the values into them. Store the result of matrix multiplication into an another 2D array, say C. | |
Write a program to store a lists of name in a List. Reverse the order of the names in the list using Stack. You should use class ArrayList to store the names (String) and class Stack for reversing.. | |
Create a class ArrSort which contains one double array to store the data and one integer variable to store the number of elements. | |
Write a program to read the content of a file and count the number of words in the file. | |
Write a program to copy contents from one file to another file. | |
Write a program to merge two file contents into another file. |
What are the principle concepts of OOPS? | |
There are four principle concepts upon which object oriented design and programming rest. They are:
| |
What is Abstraction? | |
Abstraction refers to the act of representing essential features without including the background details or explanations. | |
What is Encapsulation? | |
Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object. | |
What is the difference between abstraction and encapsulation? | |
| |
What is Inheritance? | |
Inheritance is the process by which objects of one class acquire the properties of objects of another class.
| |
What is Polymorphism? | |
Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form. | |
How does Java implement polymorphism? | |
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
| |
Explain the different forms of Polymorphism. | |
There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
| |
What is runtime polymorphism or dynamic method dispatch? | |
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable. | |
What is Dynamic Binding? | |
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance. | |
What is method overloading? | |
Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.
Note:
| |
What is method overriding? | |
Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.
Note:
| |
Can overloaded methods be override too? | |
Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future. | |
Is it possible to override the main method? | |
NO, because main is a static method. A static method can't be overridden in Java. | |
How to invoke a superclass version of an Overridden method? | |
To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method.
// From subclass super.overriddenMethod(); | |
What is super? | |
super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword.
Note:
| |
How do you prevent a method from being overridden? | |
To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy.
public final void exampleMethod() { // Method statements } | |
What is Constructor? | |
| |
How does the Java default constructor be provided? | |
If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself. | |
Can constructor be inherited? | |
No, constructor cannot be inherited, though a derived class can call the base class constructor. | |
How are this() and super() used with constructors? | |
| |
What are Access Specifiers available in Java? | |
| |
What is final modifier? | |
| |
What are the uses of final method? | |
| |
What are static variables? | |
Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier.
static type varIdentifier;where, the name of the variable is varIdentifier and its data type is specified by type. Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables. | |
What is static block? | |
Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute. | |
What is the difference between static and non-static variables? | |
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance. | |
What are static methods? | |
|