Lamda & Nested Classes Flashcards
The purpose of this is to group classes that
belong together, which makes your code more readable and
maintainable.
a class within another class
Nested Classes
Nested classes are divided into two categories:
Static (Static Nested classes).
Non-static (Inner classes).
Do not have access to other members of the enclosing
class
class OuterClass {
…
static class StaticNestedClass {
…
}
}
Static (Static Nested classes).
Have access to other members of the enclosing class, even
if they are declared private.
Non-static (Inner classes).
Why use Nested Classes?
- it is a way of logically grouping classes that are only used in one place.
- it increases encapsulation
- it can lead to more readable and maintainable code
If a declaration of a type in a particular scope has the
same name as another declaration in the enclosing scope, then the
declaration shadows the declaration of the enclosing scope. You
cannot refer to a shadowed declaration by its name alone.
Shadowing
Cannot refer directly to instance
variables or methods defined in its enclosing class: it can use
them only through an object reference:
OuterClass.StaticNestedClass
A static nested class interacts with the instance members of its
outer class (and other classes) just like any other top-level class.
In effect, a static nested class is behaviorally a top-level class
that has been nested in another top-level class for packaging
convenience.
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
Static Nested Classes
Because an inner class is associated with an
instance, it cannot define any static members itself.:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Inner Classes
two special kinds of inner classes:
Local classes
Anonymous classes.
classes that are defined in a block, which is a group of zero or more
statements between balanced braces.
Local classes
enable you to make your code more concise
They enable
you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local
class only once.
Anonymous classes
Functions as arguments. They provide a more convenient syntax for implementing a functional interface
Lamda expressions
Any interface that defines exactly one abstract method
functional interface
Lambda syntax
Argument List (a,b)
Arrow toke - >
Body {}
Why use lambdas in Java?
-A more concise syntax. Lambda expressions allow you to implement a functional interface with fewer lines of code than an
anonymous class.
- Lambdas make it easier to work with collections