0% found this document useful (0 votes)
40 views

Java Notes

The document discusses various topics related to Java programming including: 1) How to compile and run Java files using javac and java commands. 2) Rules for Java file names and package structures. 3) Different types of classes in Java like inner classes, static nested classes, anonymous classes and lambda expressions. 4) Concepts like inheritance, polymorphism, abstract classes, interfaces and generics.

Uploaded by

Taylor Maxfield
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Java Notes

The document discusses various topics related to Java programming including: 1) How to compile and run Java files using javac and java commands. 2) Rules for Java file names and package structures. 3) Different types of classes in Java like inner classes, static nested classes, anonymous classes and lambda expressions. 4) Concepts like inheritance, polymorphism, abstract classes, interfaces and generics.

Uploaded by

Taylor Maxfield
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

javac fileName.java compiles .java file and all the .

java files it refers to class files


javac *.java used to compile all java files in the current directory. This can be done if you have
unrelated files in the same directory. This should not be a common occurrence though.
java fileName runs the main method of the class file

File Names

They file name must be the same as the sole top-level public class within a file with a .java
extension:
publicClassName.java
There may be many top-level classes, as long as only one is public. THIS IS A BAD IDEA TO DO
THOUGH BECAUSE IT IS CONFUSING AND CAN LEAD TO ALL SORTS OF COMPILE ERRORS. It is
better to to use private nested classes or inner classes to accomplish the same thing.

Top-Level Class
Classes not defined within any other block or class
They can only be public or package private

Package
package package.name; must be the first line in the source code. Files in the same package
should have the same package statement. In order to make compilation easy for java, store
source files in directories whose names mirror the package name:
[src, source, etc.]/package/name/myClass.java
and put compiled files in directories that do the same
[bin, out, target, etc]/package/name/myClass.class
$CLASS_PATH is the environmental variable java will use to determine which sub
directory of the current directory to look for to place the compiled class files. If it is not set
it places them where??????????????????????????????????????????
Import
import package.name.* imports all the types in the package
import package.name.Type imports just that type
import static package.name.Type.* allows you to use static methods (i.e. functions) and static
fields (i.e. constants) contained in a type without using the Type.staticMember dot notation. For
example
import static java.lang.Math
allows you to use
cos(PI)
instead of
Math.cos(Math.PI)

package.name.Type is how you use a type without importing its package


Access Level Modifiers

Other Modifiers
abstract
method has no body, just a semicolon. It is meant to be implemented in a
subclass
class cannot be instantiated. Is the only kind that can contain abstract methods
final
variables cannot be reassigned a different value
fields cannot be reassigned a different value
method cannot be overridden by a subclass
class cannot be extended

static
variables
method cant access non-static fields

Class Members
consist of fields, methods, and nested classes
Outer class
Are top-level classes so can only be public or package private
Nested class
A class defined within another class. The two types are Static Nested Classes and Inner Classes
Can be private, public, protected, or package private
Inner Class
Use: They are used to logically group related classes whose fields are dependent on each other

Inner classes are non-static nested classes


They have access to the all the members (fields and methods) of the enclosing class because they
are instantiated from instance of the enclosing class
THIS MEANS THE INNERCLASS CONSTRUCTOR IS AN INSTANCE METHOD OF THE OUTERCLASS.
To instantiate an inner class you must first create an instance of the outer class and then call
the inner class constructor as a method of it:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Static Nested Class
Use: They used to logically group related classes together

Static nested classes DON'T HAVE ACCESS to the members (fields and methods) of the enclosing
class.
They interact with their outer class and other classes just like any other top-level class.
They are accessed using the enclosing class name:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass()

Local classes
local classes are classes defined in a block (a group of zero or more statements betweeen braces).
They can be defined in methods, if clause, for loops etc.
They have access to the members of its enclosing class
They have access to final and effectively final local variables and capture (i.e. like a closure) their
values.
They cannot have any static members except for
constant variables variables type String or a primitive type that is final and initialized
with a compile-time constant expression
Local interfaces are not allowed
example local class:
Anonymous Classes
Are nameless local classes that must implement an interface or extend a class that are
declared and instantiated at the same time

This means they can't declare there own constructor any must use their default construct
(Any fields they have must be initialized with the values you want in the class body).

Even though they must implement an interface or extend a class, they can define extra
methods (but they can only be called inside the class).

They are in expressions so must end in a semicolon. :


Lambda Expressions
(a, b) -> { System.out.println(a); return a + 2;}
a -> a + 2
Are special anonymous classes who implement a functional interface

functional interface which are interfaces with only one abstract method.

There based on the parameter of the method they are passed to, or the type of the parameter
they are assigned to.

java.util.function defines standard functional interfaces which you should use when you want a
method to accept lambdas or create a variable storing a lambda. For example using the Predicate
interface

And using the java.util.function.BiFunction interface (whose single abstract method is


apply()) to create a lambda variable:
Constructors
If no constructor is defined for a Class then the Java compiler will create one of the form
ClassName() {}

If you define a constructor NO EMPTY DEFAULT CONSTRUCTOR IS CREATED


so it may cause errors when you try subclass it with a class.

Static Block?????????????
Static blocks
Initializer Blocks????????????

Varargs
(Type... parameterName)
allows an arbitray number of input parameters of the SAME type to a method or constructor.
IT STORES THE ARGUMENTS IN AN ARRAY

Abstract Class
public abstract class MyClass {}
a class that cannot be instantiated
They can contain
abstract methods
abstract void draw();
or regular methods
void draw() {}
fields
int max = 100;
int count;

Interface
A special abstract class that allows classes to implement multiple of them do to them only
containing static fields
all methods with a semicolon instead of a body are abstract
all fields are public static final

You can also put


static methods
default methods where you provide a default implementation that will be used if
the implementing class does not override it. Mostly used for adding methods to
interfaces at a latter date without breaking users code.

Implements
public class RectanglePuls implements Relatable {}

Inheritance
class Subclass extends SuperClass {}

subclasses inherit all members (fields, methods, and nested classes) from their superclass, but
not Constructors(as these are not members). THEREFORE you must invoke the superclasses
constructor using super(arguments1, argument2 .. etc):
overrideing if a subclass contains a method with the same signature (name, and parameter types)
and return type then that method will automatically override the superclasses method at
runtime

USE @Override to allow compiler to do runtime checks on method to make sure it matches
the superclass’s method

When you create an instance of a Subclass the following


items happen:
Superclass’s initialization blocks run
Superclass’s field initialization
Superclass’ empty constructor [super()] is called implicity [unless
super(arguments, .. etc) is called explicitly as first line in the subclass's constructor].
This will cause an error if the Superclass defined an constructors (thus getting
rid of the default empty constructor)without defining its own empty
constructor to replace the default !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Subclass initialization blocks run
Subclass field initialization
Subclass constructor called

Generics
type parameter is what you call T in ClassName<T>
parameterized type is what you call the full ClassName<T>

Type parameters can be regular types or parameterized types:


OrderedPair<String, Box<Integer>> p = new OrderedPair<>("some integer", new
Box<Integer>())
generic class
public class Pair<K, V> { /**/ }
Can be called with explicit types:
Pair<Integer, String> pair = new Pair<Integer, String>(1, "some string");
or the types can be inferred by the compiler implicitly using type inference. This is done
using the empty diamond.
Pair<Integer, String> pair = new Pair<>(1, "some string");
generic methods
public <K, V> boolean compare(K p1, V p2) {/**/}
Can be called with explicit types
a.<Integer, String>compare(p1, p2);
or the types can be inferred by the compiler implicitly using type inference:
a.compare(p1, p2);

Bounded Type Parameters


<B extends ARealType> means that the type argument provided to parameterized type
must be of type ARealType or a subclass of ARealType.
This allows you to use ARealType methods with variables of type B in your
method or classs:

multiple bounds extends also excepts multiple interfaces

"is a" relationship


ArrayList<T> is a subclass of List<T>
ArrayList<String> is a subclass of List<String>

interface PayloadList<E,P> extends List<E> {/**/}


PayloadList<String, Integer> is a subclass of List<Integer>

but in this example where class B extends A {/**/}


ArrayList<B> is not a subclass of ArrayList<A>

use-site variance java notation


Collection<? extends E> allows one to get items from the collection but not put things in it. It
accepts E and its subtypes. This is called covariance. Read but not write. Producers
Collection <? super E> allows one to put things in a collection but not get things. It accepts E and
all its supertypes. This is called contravarience. Write but not read. Consumers

Extras
var allows type inference on the left side
instead of:
Pair<Integer, String> pair = new Pair<Integer, String>(1, "hello");
or
Pair<Integer, String> pair = new Pair<>(1, "hello")
can use:
var pair = new Pair<>(1, "hello")

text block strings are strings preceded by three double quotes """ followed by a new line (which
is ignored in the string), and ending with just three double quotes """ (if you add a new line before
the ending quotes then a new line will be included in the actual string). This preceding new line is
mandatory, thus you can't have single line text block strings. Thus:

becomes:

The compiler takes out all white space to the left of the ending """ so:
will compile to:

but:

will compile to

if you want to control the white space without adding a new line you must use these
methods on the string block
.indent(int spacesToIndentEachLine)

within a text block, escaping characters (e.g. \', \n, \t, \") is not usually required

string interpolation java does not directly support string interpolation yet. Instead use
String::formatted
var s = "x:%d, y%d, z%d".formatted(x, y, z)

try with resources a try statement that declares one or more resources implementing
java.lang.AutoCloseable (which includes all java.io.Closable objects), between
parenthesis. These resources are automatically closed when the the program is finished:
This
allows you to
use these
resources without using a finally block to close them manually

pattern matching for instanceof allows you to specify a binding variable whose scope depends
on the return value of an instance of expression:

POJO (Plain Old Java Object) is a Java object that does not follow any major Java object models,
conventions or frameworks. Therefore it does not have to extend any pre-specified classes,
implement pre-specified interfaces, or contain pre-specified annotations
JavaBean is a serializable POJO (Plain Old Java Object) that has a zero-argument constructor,
and allows access to properties using getter and setter methods following a simple naming
convention.

java.nio new input/output package that has a better api than the old package

jshell command that runs the java shell to run java code in the terminal

instance.classs will return a Class<T> repressentation of the object's class

You might also like