Java Learning: Inner classes and exceptions

Source: Internet
Author: User

Java learning interrupted more than half a month, today is the next study. Today we have learned about inner classes and exceptions, and here is today's summary.


First look at the inner class.

Define another class in a class, which is called an inner class or a built-in class (inner Class).

An inner class allows us to organize logically related sets of classes and to control the visibility of inner classes by external classes (outer Class).

When we set up a inner class, the object has a relationship with the Outer class object, which is formed by a special this reference, allowing the inner class object to arbitrarily access all members of the external class. The following figure illustrates this special this reference.


The object o of a outer class is declared in the main function, and when it calls the Print method, the This pointer is generated, and the object I of the inner is declared in the Print method, and I has the this pointer when I call the Print method of I. At the same time, the inner class has a outer.this this pointer to the object of the Outer class, outer.this this pointer is the special this reference.

An inner class can be placed not only in a class, but also in a method or in a statement block.


The inner class defined in the method, if you want to access the parameters of the local variable or method defined in the method, the variable must be declared final, and it will be initialized at the time of declaration, accessible only, and not changed.

An inner class can be declared private, protected, abstract, or final. The permissions are the same as those of these modifiers.

Also, an inner class can be declared static, but it is no longer possible to use the non-static member variables of the outer class and the non static member methods. Members in a non-static inner class cannot be declared static, and only the top-level class or static inner class can declare a static member.


Said so much, but still do not know why to use the inner class.

First of all, in the inner class, we are free to access the members of the external classes, but also allows us to better organize the management of our code, enhance the readability of the code.

Second, the inner class can be used to create the adapter class, which is the class that implements the interface, uses the inner class to implement the interface, and can better position the method associated with the interface in the code.

Third, the inner class can make a variety of methods. For example, it is now necessary to inherit a class and implement an interface, and they have a common method, how to deal with it. The following section of the code is clear.

Interface Machine
{
void run ();
}


Class Person
{
void Run ()
{
System.out.println ("Run");
}
}


Class Robot extends Person
{
Private class Machineheart implements Machine
{
public void Run ()
{
System.out.println ("Heart Run");
}
}
Machine Getmachine ()
{
return new Machineheart ();
}
}


Class Test
{
public static void Main (string[] args)
{
Robot robot=new Robot ();
Machine M=robot.getmachine ();
M.run ();
Robot.run ();
}
}

This piece of code is a good solution to the above problems.


After a general understanding of the internal class, it began to contact the exception.

An exception is thrown when a file that is not in the village is opened, the network connection is interrupted, the array subscript is out of bounds, the class file being loaded is missing, and so on.

In Java, two related classes are defined, one is an exception class and the other is an error class. The exception class defines the minor error conditions encountered in the program, and the error class defines critical error conditions that cannot be recovered in the program, such as memory overflow, class file format errors, and so on, which are handled by the Java Runtime system and do not need to be processed.

So what to do with the exception.

If an exception occurs during the execution of a Java program, an exception class object is automatically generated, which is referred to the Java Run-time system, which is called throwing an exception.

When the Java runtime system receives an exception object, it looks for code that can handle the exception and hands the current exception object to its processing, a process known as catching an exception.

If the Java runtime system cannot find a method that can catch exceptions, the runtime system terminates and the corresponding Java program exits.

Handling exceptions is primarily the use of try/catch/finally statements.

For runtimeexception, we usually do not need to capture, such exceptions are automatically thrown by the Java runtime system and processed automatically.

If a method in the parent class throws more than one exception, the overlay method in the subclass either throws the same exception, or throws the subclass of the exception, but does not throw a new exception, of course, outside of the construction method.

When we declare a method, we declare an exception that is not thrown, and the Java compiler forces the user of the method to handle the exception, which is commonly used in abstract base class and interface.

Here is a piece of code, familiar with the handling of exceptions.

Import java.io.*;
Class Excep
{
Excep () throws ArithmeticException
{
}
public int Division (int a,int b) throws Arithmeticexception,divisorisminusexception//exception
{
Try
//{
if (b<0)
throw new Divisorisminusexception ("Divisor can ' t be minus");
return a/b;
/*}
catch (ArithmeticException e)
{

E.printstacktrace ();
throw new Exception ("Can ' t divide by Zero");
Throw e;
return 0;
}*/

}
public int fn1 (int a,int b) throws Arithmeticexception,divisorisminusexception//exception
{
Return division (A,B);
}
}


Class Childexcep extends Excep
{
Childexcep () throws FileNotFoundException
{
}
public int Division (int a,int b) throws Arithmeticexception,divisorisminusexception
{
return a/b;
}
}
Class Divisorisminusexception extends Exception
{
Divisorisminusexception (String str)
{
Super (STR);
}
}
Class Exceptest
{
public static int method1 (EXCEP excep)
{
Try
{
Return excep.division (5,0);
}
catch (ArithmeticException e)
{
System.out.println (E.tostring ());
}
catch (Divisorisminusexception ex)
{
System.out.println (Ex.tostring ());
System.exit (-1);
Return
}
return 0;
}
public static void Main (string[] args)//throws Exception
{
Childexcep ce=new childexcep ();
Method1 (CE);
Excep excep=new excep ();
Try
{
Excep.division (5,0);
EXCEP.FN1 (5,-1);
SYSTEM.OUT.PRINTLN ("exception");
Return
}

catch (ArithmeticException e)
{
System.out.println (E.tostring ());
}
catch (Divisorisminusexception ex)
{
System.out.println (Ex.tostring ());
System.exit (-1);
Return
}
catch (Exception e)
{
System.out.println ("Can ' t divide by Zero");
System.out.println (E.getmessage ());
System.out.println (E.tostring ());
E.printstacktrace ();
}
Finally
{
System.out.println ("finally");
}
System.out.println ("Finish");
}
}

Let's look at the structure of the anomaly again.



The above is the general content of today's study, because the mood is still not completely slow down, so write a bit of chaos, the process of learning is also always wandering, their thinking a little less. Hey, slow down, feelings this thing ....


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.