Why are interfaces sometimes declared within classes

Java "introduction"

introduction

This tutorial is not an "introduction" in the strict sense of the word. Only a few selected topics are covered. The selection of the topics covered is based on the experiences from the practical course in Scientific Computing and Numerical Mathematics; frequently asked questions and some problem areas should be covered.
Furthermore, the topics are by no means dealt with in full in this introduction; instead, only a few aspects are explained using examples. For further information, I recommend the online book Java is also an island.

Variables in Java

Variables are used in Java to store data. Each variable has a type (Data type). This data type specifies the type of data that can be stored in the variable.
There are basically two types of data types in Java: Primitive data types and Reference types (also Class types). The primitive data types include boolean, char, short, int, long, float, double.
The class types are determined by the programmer, so every Java class represents such a class type.

Before a variable can be used to store data, it must declared (also Are defined), it always happens in the same way: type name variable name;
In which Type name is the name of the type of the variable, and Variable name is the name of the variable under which it can then be addressed.

Scopes of variables

In a Java program, a variable cannot be accessed from everywhere. The deciding factor about where the variable is visible (usable) (scope) is essentially the place of the declaration.
There are three types of variables in Java with regard to the scope: Class variables, Object variables and local variables.
  • Class variables - are visible within a whole class. A class variable is created within a class with the help of the keyword static declared: static type name variable name; Such a variable is then also available in every object of this class and therefore always has the same value regardless of the respective object;


  • Object variables - are visible within an object. An object variable is declared like a class variable within a class: type name variable name; Such a variable can have a different value in each object of this class. Strictly speaking, a new variable with the same name is created for each new object;

  • Local variables - are within Blocks visible in which they were declared. A block is defined by curly braces, i.e. a method;
Here is an example of the scope of the variables:
  1. public class my class {

  2. staticint number; // class variable

  3. double length; // object variable

  4.  

  5. publicvoidmyMethod ()

  6. {

  7. int k = 0;

  8.  

  9. for (int i = 0; i <100; i ++)

  10. {

  11. k = k + i;

  12. } // end for

  13.  

  14. } // end myMethod

  15.  

  16. } // end class myclass

The variable k is only within the method my method visible and i only inside the for loop.

Note: It should be noted that the class variables and object variables are automatically initialized with zero, the local variables, on the other hand, always have to be initialized "manually";

Transfer of variables

In Java, the variables of primitive data types and reference types are handled in different ways when they are passed:
when a variable of a primitive data type is transferred, the value of the variable is copied (Call by Value), in the case of a reference type, however, only the reference (the reference) is copied so that the new variable refers to the same object. The difference can be explained more easily with an example: we compare the primitives data type int, and the class type we have defined myIntwhich does nothing more than a variable of type int to encapsulate
  1. public class meinInt {

  2. publicint value;

  3. } // end class myInt

In the following class there are now two variables of type int and myInt created, and then to the respective methods inc Handed over:
  1. public class callTester {

  2.  

  3. public staticvoidmain (String [] args)

  4. {

  5. int i = 0;

  6. myInt j = newmyInt ();

  7.  

  8. inc (i);

  9. inc (j);

  10.  

  11. System.out.println (i);

  12. System.out.println (j.value);

  13. } // end main

  14.  

  15.  

  16. private staticvoidinc (int k)

  17. {

  18. k = k +1;

  19. } // end inc

  20.  

  21.  

  22. private staticvoidinc (myInt k)

  23. {

  24. k.value = k.value +1;

  25. } // end inc

  26.  

  27. } // end class callTester

The methods inc have the same effect in both cases: in the case of int the transferred value is increased by one, and in the case of myInt the encapsulated value is increased by one, but nothing is returned. After executing it, we get the output 0
1
That means that the value of i has not been changed, but the value within j (!). The following graphic illustrates what happened when the variables were transferred:


The angular boxes mark storage cells. The changes in the variable k in the method inc (int k) have no effect on the variable i, in contrast to inc (myInt k), Where j and k access the same object.

Note: The same procedure is used when assigning the variables: a = b;
In the case of a primitive data type, the value is copied (new memory area); in the case of a reference type, only the reference is copied; both variables then refer to the same thing Object;

Classes and objects

Java is an object-oriented programming language. What objects are, how to create them and how to use them will now be briefly explained. A Java program essentially consists of classes. A class describes the properties of the objects and can be viewed as a template. The objects are then realizations of a class and are also referred to as instances.

Here is a simple example for a Java class:
  1. public class quadratic function implements function

  2. {

  3.  

  4. // coefficients

  5. privatedouble a;

  6. privatedouble b;

  7. privatedouble c;

  8.  

  9. / ** Creates a new instance of the quadratic function class * /

  10. public square function (double a, double b, double c)

  11. {

  12. this.a = a;

  13. this.b = b;

  14. this.c = c;

  15. } // end constructor quadratic function

  16.  

  17.  

  18. public doublef (double x)

  19. {

  20. return a + b * x + c * Math.pow (x, 2);

  21. } // end f

  22.  

  23. } // end class quadratic function


This class describes a simple quadratic function f (x) = a + bx + bx ^ 2. An important part of a class is the constructor. The constructor is a special method that is used to create an object. Everything that has to be done to create an object of a class is in the constructor, e.g. initialization of the variables.
Note: A class can have several constructors, but these must then differ in the parameter list;

Creation of objects

An object of a class can be found in java with the help of the operator new produce. So the line new creates myClass ();
an object of the class myClass. In order to be able to access the created object, we need a reference that refers to this object. The following statement creates a reference of the class my class: myclass name;
Note: Only objects of compatible classes can be assigned to a reference.
The following lines now cause a reference to the class my class is created and object of the class my class generated and the reference Surname is assigned: myclass name;
name = new myClass ();
Note: The following short notation is allowed in Java myClass name = new myClass ();
Often the references are used synonymously with the objects to which they refer. In most cases this distinction is not necessary, but we will also see cases in which this distinction is absolutely necessary.
Note: Several references can refer to the same object: e.g .: myclass name2 = name;
The following graphic illustrates the difference between the object and the reference:



Note: the corresponding constructor is called when objects are created;

Access to properties of the objects

Classes are defined by their properties (variables and methods) and thus also objects of these classes. These properties can be accessed from "outside". To access the internal properties of a class or an object, the operator "." uses: double y = name.f (2);
In this case we call the object method "f" and thus get the value of the function at position 2;
Note: With "." we can only access the properties of the objects that are "released", in our example we cannot access the variables a, b and c directly, i.e. double u = name.a
will not work. So here are some keywords that define the rights for access to the internal properties of a class:
  • public - specifies that the property can be accessed from any class or object;
  • protected - specifies that the property can only be accessed from the classes (objects) derived from this class;
  • private - specifies that on the property Not can be accessed from outside;
Note: At this point, properties are understood to mean methods and variables;
Note: if no keyword is used explicitly, the variable is automatic public;

Inheritance in Java

The classes are defined in Java by their properties (methods and variables). A class can pass on these properties to other classes. This is done with the help of the keyword extends. Let us now consider the following class as an example:
  1. public class linear function extends quadratic function

  2. {

  3. / ** Creates a new instance of the quadratic function class * /

  4. publiclineareFunction (double a, double b)

  5. {

  6. super (a, b, 0);

  7. } // end constructor linearFunction

  8.  

  9. } // end class linear function

one says the class linear function "inherits" or "is derived" from the class quadratic function. That way, the class owns linear function all properties of the class quadratic function, especially the variables ABC and the method public double f (double x).

Note:Super(...) calls the corresponding constructor of the parent class;

Interfaces

Interfaces are classes that only contain signatures of methods but no implementation.
An example of an interface:
  1. public interface function

  2. {

  3. doublef (double x);

  4. } // end interface function

In line 3. the signature of the method f (double x) but the exact implementation is missing. Objects cannot be created from an interface; an interface specifies which methods have a class got tothat implements this interface. If a class is to implement an interface, it is done with the keyword implements public class quadratic function implements function
{
...
}
In this example, the class quadratic function a method public double f (double x) contain.
To clarify the necessity of interfaces we consider the following example: Suppose we want to implement a method that approximates the derivative of any one-dimensional function at a certain point. The function is passed as an object of any class. How exactly the function is implemented and what other properties this class has are not of interest to us at this point: it is important for us that this class has a method public double f (double x) that owns us the value of the function at the point x supplies. So we are writing a method that accepts objects of a class as parameters that use the interface function implemented

  1. private static double derivative (function f, double x)

  2. {

  3. double h = 1e-4;


  4. double delta = (x + h) * h;


  5. double derivative = (f.f (x + delta) - f.f (x)) / delta;


  6. return derivative;

  7. } // end derivative

Thus, the user of this method has all the freedom to implement his function and name the class :)

Error handling in Java

Every good program needs good error handling. Java uses the concept of Exception (Exceptions). Every time an error occurs while a Java program is being executed, an exception is generated ("thrown") which can then later be "caught" and handled in the right place. Strictly speaking, it is usually an object of the class Exception, or a derived class and passed up. This object contains the information about the error. If an exception occurs in a method, it can either be caught or forwarded. If an exception reaches the very top, the execution of the program is interrupted and a corresponding error message is output.
To the throw, hand off and intercept exceptions are in java constructs throw, throws and try-catch are available which will now be explained in more detail.

Forward exceptions

If a method is to forward the exceptions, it can be specified as in the following example: public static void myMethode () throws exceptionClass1, exceptionClass2, ..., exceptionClassN
{
...
}
When declaring the method, throws Specifies which classes of exceptions are to be forwarded: all exceptions are forwarded that belong to the classes in the throws List, or belong to derived classes.
Note: If all possible exceptions are to be forwarded, it is usually only sufficient to specify the class Exceptions;

Catch exceptions

Sometimes it is not desirable for the program to crash on an error such as an incorrect entry. To prevent this from happening, the appropriate exceptions intercepted become. This is what Java stands for try ... catch Construct available that is used as follows: try
{
Instruction 1;
Instruction 2;
.
.
.
}
catch (ExceptionTyp1 e)
{
Exception Instructions1;
}
.
.
.
catch (ExceptionTypN e)
{
Exception InstructionsN;
}
In normal program execution, the instructions within the try Blocks executed, if an error occurs, an exception is thrown, which is then triggered by one of the catch Blocks can be intercepted. The execution of the "normal" instructions is interrupted and a "suitable" catch Jumped block. A catch (class type name e) Block can only catch exceptions of type Class type name or are of a derived class type.
Note: usually all exceptions belong to the class Exception derived classes, so try
{
...
}
catch (exception e)
{
...
}
catches all exceptions;

Generate exceptions

Very often it is more convenient to indicate the failure of an operation by throwing an exception instead of checking the return values. Consider the following example:


  1. public staticdoubledivide (double x, double y) throwsException

  2.  

  3. return x / y;

  4.  

  5. } // end divide

For example, the method is now called as follows z = divide (1.0) so is used as the return value Infinity returned, which can lead to incorrect results if one continues to calculate. We consider division by 0 as an error and, if necessary, want to throw an exception to the calling method:


  1. public staticdoubledivide (double x, double y) throwsException

  2. {

  3. if (y == 0)

  4. throw newException ("Division by NULL.");

  5.  

  6. return x / y;

  7. } // end divide

Note:throws exception indicates that there are exceptions to the class Exception should not be dealt with in the method, but should be passed on;
Note: the line throw new Exception ("Division by NULL."); causes an exception to the class Exception is generated with the corresponding message;