1) How to redirect System.out.println() output to file or some other out stream?By default SOP(System.out.println) prints out put on console. It is possible to redirect out put to some other file. See following sample code.
package jobset_qa.jobs;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class PrintToFile
{
public PrintToFile() { }
public static void main(String argv[]) throws FileNotFoundException
{
System.out.println("This will be printed in console..");
PrintStream fileout=new PrintStream("systemoutput.txt");
System.setOut(fileout);
System.out.println("From now.. the messages would be systemoutput.txt");
System.out.println("You ust be seeing this message in systemoutput.txt file");
}
}
Polymorphism :-Means one name, many forms.This can be achived in following two ways.
- Method overloading : overload differs in the number or type of its arguments. Differences in argument names are not significant. A different return type is permitted, but is not sufficient by itself to distinguish an overloading method.
- Method Overriding : override has identical argument types and order, identical return type, and is not less accessible than the original method. The overriding method must not throw any checked exceptions that were not declared for the original method."
There are two farm of polymorphism
- Compile-time polymorphism
- Runtime polymorphism
Compile-Time Polymorphism :- Method overloading as a form of compile-time polymorphism. Compiler determines which method (from a group of overloaded methods) will be executed, and this decision is made when the program is compiled.
Runtime Polymorphism : - This is based on method overriding. The decision as to which version of a method will be executed is based on the actual type of object whose reference is stored in the reference variable, and not on the type of the reference variable on which the method is invoked.This is sometimes referred to as late binding.
Sample Code :-
class A extends Object{ //Super Class
public void m(){
System.out.println("m in class A");
}//end method m()
}//end class A
class B extends A{ // Sub Class
public void m(){
System.out.println("m in class B");
}//end method m()
}//end class B
public class Poly03{
public static void main( String[] args){
Object var = new B();
((A)var).m(); }}
The Method Output is : m in class B
This confirms that even though the type of the reference was converted to type A, (rather than type Object or type B), the overridden version of the method defined in class B was actually executed.