Sunteți pe pagina 1din 11

Extra Innings

Inner classes
Means defining another class within another class. If class B is within A then B is known in A but not outside A. Enclosed class (B above) has access to all members of enclosing class. (A above) Enclosing class does not have access to members of enclosed class.

Types of Nested classes


static and Non-static (inner class) Static class has modifier static before it, because it is static it must access members of its enclosing class using objects, if they are not static. A non-static or inner class can access members of enclosing class directly.

class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); }
// this is an innner class class Inner { void display() { System.out.println("display: outer_x = " + outer_x); } } }

class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } } //Innerclass is known only within the //Outerclass, hence we cannot create an //object of Innerclass in main() method.

Where can we define nested classes? And benefits


Inside another class but outside of all methods. Inside any method of outer class. Inside any block within method of outer class. In general anywhere within a class. Useful when handling events in applets( chapter-20) There exist anonymous inner classes having no names.

Overriding toString method() and valueOf()


Originally defined in the String class When overriding toString() must be declared as public. valueOf() called automatically when println() called with argument as some system defined object and only when we override toString() for a user defined object which in turn calls toString(). ValueOf() is overloaded for simple data types and converts them into a String without calling toString() method. Complete Syntax: String toString()

class TO { int x; public String toString() { return("Java Java Mahiya Ve.."); } public static void main(String args[]) { TO obj = new TO(); System.out.println(obj); System.out.println(5); System.out.println(new IllegalAccessException()); } }

Converting data
import java.io.*; class Convert { public static void main(String args[]) { int i = 0; double k = 0; try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); i = Integer.parseInt(br.readLine()); k = Double.parseDouble(br.readLine()); } catch(IOException e) { } System.out.println(i + k); } }

parseInt()
Exists for byte, short, int, long, double but NOT for float. Converts compatible string to appropriate data type. For example: giving 45.678 for parseInt produces error Example: giving Kehva123 produces error. All these throw NumberFormatException

S-ar putea să vă placă și