• No results found

Non-static nested class (inner class) 1 Member inner class

1.2 Anonymous inner class 1.3 Local inner class 2. Static nested class

Type Description

Member Inner Class

A class created within class and outside method.

Anonymous Inner Class

A class created for implementing interface or extending class. Its name is decided by the java compiler.

Local Inner Class

A class created within method.

Static Nested Class

A static class created within class.

Nested Interface

An interface created within class or interface.

 Java inner class or nested class is a class which is declared inside the class or interface.

 We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable.

 Additionally, it can access all the members of outer class including private data members and methods.

Advantages

 Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private.

 Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.

 Code Optimization: It requires less code to write.

Difference between nested class and inner class in Java

 Inner class is a type of nested class. Non-static nested classes are known as inner classes.

Examples of nested classes Example 1: Static Nested class

Syntax:

class Outer_Class_Name {

static class Nested_class_Name { } Example 2: Non Static Nested Class ( Inner Class)

Syntax:

class Outer_Demo { class Inner_Demo { }

}

Code:

// Accessing the inner class from the method within void display_Inner() {

public static void main(String args[]) { // Instantiating the outer class

 Inner classes are also used to access the private members of a class

 To instantiate the inner class, initially you have to instantiate the outer class.

Syntax to do so is as follows :

Outer_Class_Name outer = new Outer_Class_Name();

Outer_Class_Name.Inner_Class_Name inner = outer.new Inner_Class_Name();

//Program to demonstrate accessing the Private Members using inner class class Outer_Demo {

public static void main(String args[]) { // Instantiating the outer class

Outer_Demo outer = new Outer_Demo();

// Instantiating the inner class

Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();

System.out.println(inner.getNum());

} }

Example 3 : Local inner class example

 In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method.

public class Outerclass {

MethodInner_Demo inner = new MethodInner_Demo();

inner.print();

}

public static void main(String args[]) { Outerclass outer = new Outerclass();

outer.my_Method();

} }

Example 4: Anonymous Inner Class

!!Note: Please do not go through this before having concept of inheritance, abstract class and interface in java.

 An inner class declared without a class name is known as an anonymous inner class. In case of anonymous inner classes, we declare and instantiate them at the same time. Generally, they are used whenever you need to override the method of a class or an interface. The syntax of an anonymous inner class is as follows –

AnonymousInner an_inner = new AnonymousInner() { public void my_method() {

public abstract void mymethod();

}

public class Outer_class {

public static void main(String args[]) {

AnonymousInner inner = new AnonymousInner() {

Exploring the String Class

 String is probably the most commonly used class in Java’s class library. The obvious reason for this is that strings are a very important part of programming.

 The first thing to understand about strings is that every string you create is actually an object of type String. Even string constants are actually String objects. For example, in the statement

the string "This is a String, too" is a String object.

 The second thing to understand about strings is that objects of type String are

immutable; once a String object is created, its contents cannot be altered. While this may seem like a serious restriction, it is not, for two reasons:

o If you need to change a string, you can always create a new one that contains the modifications.

o Java defines peer classes of String, called StringBuffer and StringBuilder, which allow strings to be altered, so all of the normal string manipulations are still available in Java.

 Strings can be constructed in a variety of ways. The easiest is to use a statement like this:

 Once you have created a String object, you can use it anywhere that a string is allowed.

For example, this statement displays myString:

 Java defines one operator for String objects: +. It is used to concatenate two strings. For example, this statement

results in myString containing "I like Java."

 The String class contains several methods that you can use. Here are a few.

o You can test two strings for equality by using equals( ).

o You can obtain the length of a string by calling the length( ) method.

o You can obtain the character at a specified index within a string by calling charAt( ).

o The general forms of these three methods are shown here:

boolean equals(secondStr) int length( )

char charAt(index)

 We can have arrays of strings, just like we can have arrays of any other type of object.

Using Command-Line Arguments

 Sometimes you will want to pass information into a program when you run it. This is accomplished by passing command-line arguments to main( ).

 A command-line argument is the information that directly follows the program’s name on the command line when it is executed.

 To access the command-line arguments inside a Java program is quite easy—

 they are stored as strings in a String array passed to the args parameter of main( ).

 The first command-line argument is stored at args[0], the second at args[1], and so on.

 All command-line arguments are passed as strings. You must convert numeric values to their internal forms manually

For example, the following program displays all of the command-line arguments that it is called with:

Varargs: Variable-Length Arguments

Beginning with JDK 5, Java has included a feature that simplifies the creation of methods that need to take a variable number of arguments. This feature is called varargs and it is short for variable-length arguments.

Prior to JDK 5, variable-length arguments could be handled two ways. One using overloaded method (one for each) and another put the arguments into an array, and then pass this array to the method. Both of them are potentially error-prone and require more code. The varargs feature offers a simpler, better option.

 A method that takes a variable number of arguments is called a variable-arity method, or simply a varargs method.

 The varrags allows the method to accept zero or multiple arguments.

 The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:

return_type method_name(data_type... variableName){

//body }

 the … causes the parameter to be treated as an array of the specified type

 A method can have “normal” parameters along with a variable-length parameter.

However, the variable-length parameter must be the last parameter declared by the method

In this case, the first three arguments used in a call to doIt( ) are matched to the first three parameters. Then, any remaining arguments are assumed to belong to vals

 Rules for varargs:

 While using the varargs, you must follow some rules otherwise program code won't compile. The rules are as follows:

 There can be only one variable argument in the method.

 Variable argument (varargs) must be the last argument.

These are invalid

void method(String... a, int... b){}//Compile time error

void method(int... a, String b){}//Compile time error

// Java program to demonstrate varargs class Test1

{

// A method that takes variable number of intger // arguments.

static void fun(int ...a) {

System.out.println("Number of arguments: " + a.length);

// using for each loop to display contents of a for (int i: a)

System.out.print(i + " ");

System.out.println();

}

public static void main(String args[]) {

// Calling the varargs method with different number // of parameters

// Java program to demonstrate varargs with normal arguments class Test2

{

// Takes string as a argument followed by varargs static void myMethod(String str, int ...a)

{

System.out.println("String: " + str);

System.out.println("Number of arguments is: "+ a.length);

// using for each loop to display contents of a for (int i: a)

System.out.print(i + " ");

System.out.println();

}

public static void main(String args[]) {

// Calling myMethod() with different parameter myMethod("Tribhuvan University ", 100, 200);

myMethod("CSIT", 1, 2, 3, 4, 5);

myMethod("BIM");

} }

Overloading Vararg Methods

 Overloading allows different methods to have same name, but different signatures where signature can differ by number of input parameters or type of input parameters or both.

 We can overload a method that takes a variable-length argument

 We can overload a method that takes a variable-length argument by two ways.

 First, the types of its vararg parameter can differ.

This is the case for vaTest(int …) and vaTest(boolean …). Remember, the … causes the parameter to be treated as an array of the specified type. Therefore, just as you can overload methods by using different types of array parameters, you can overload vararg methods by using different types of varargs. In this case, Java uses the type difference to determine which overloaded method to call.

 The second way to overload a varargs method is to add one or more normal parameters. This is what is done with vaTest(String, int …). In this case, Java uses both the number of arguments and the type of the arguments to determine which method to call. In this case, Java uses both the number of arguments and the type of the arguments to determine which method to call.

These two ways can be summarized as :

Related documents