Static Import

This feature enables us to import the static members of a class by specifying only it's name no need of class name also.

// Compute the hypotenuse of a right triangle.
public class Hypot
 {
 public static void main(String args[]) 
 {
 double side1, side2;
 double hypot;
 side1 = 3.0;
 side2 = 4.0;
 // Notice how sqrt() and pow() must be qualified by their class name, which is Math.
 hypot = Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2));
 System.out.println("Given sides of lengths " + side1 + " and " + side2 + " the hypotenuse is " + hypot);
 }
}

Output:

Given sides of lengths 3.0 and 4.0 the hypotenuse is 5.0

// Use static import to bring sqrt() and pow() into view.
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
// Compute the hypotenuse of a right triangle.
public class Hypot
 {
 public static void main(String args[]) 
 {
 double side1, side2;
 double hypot;
 side1 = 3.0;
 side2 = 4.0;
 // Notice how sqrt() and pow() must be qualified by their class name, which is Math.
 hypot = sqrt(pow(side1, 2) + pow(side2, 2));
 System.out.println("Given sides of lengths " + side1 + " and " + side2 + " the hypotenuse is " + hypot);
 }
}

Output:

Given sides of lengths 3.0 and 4.0 the hypotenuse is 5.0

Invoking Overloaded Constructors Through this( )

While overloading constructors in java we caninvoke one constructor in anotherconstructor by using this() as follows

this(arg-list)-

The overloaded constructor that matches the parameter list specified by arg-list is executed first. Then the reaming statements in original constructor will executed. The call to this( ) must be the first statement within the constructor.

class MyClass {
 int a;
 int b;
 // initialize a and b individually
 MyClass(int i, int j) {
 a = i;
 b = j;
System.out.println("Two argumetns::"+a+" "+b);
 }
 // initialize a and b to the same value
 MyClass(int i) {
 a = i;
 b = i;
System.out.println("one argument::"+a+" "+b);
 }
 // give a and b default values of 0
 MyClass( ) {
 a = 0;
 b = 0;
System.out.println("default::"+a+ " "+b);
 }
}
public class Simple
{
public static void main(String args[])
{
MyClass ob1=new MyClass(3,4);
MyClass ob2=new MyClass(35);
MyClass ob3=new MyClass();
}
}

Output:

Two argumetns::3 4

one argument::35 35

default::0 0

//using this(arglist) to invoke overload constructors
class MyClass 
{
 int a;
 int b;
 // initialize a and b individually
 MyClass(int i, int j) {
 a = i;
 b = j;
System.out.println("values of a and b::"+a+" "+b);
 }
// initialize a and b to the same value
 MyClass(int i) 
{
 this(i, i); // invokes MyClass(i, i)
 }
 // give a and b default values of 0
 MyClass( ) 
{
 this(0); // invokes MyClass(0)
 }

}
public class Simple
{
public static void main(String args[])
{
MyClass ob1=new MyClass(3,4);
MyClass ob2=new MyClass(35);
MyClass ob3=new MyClass();
}
}

results matching ""

    No results matching ""