Java
Java
System.out.println()
Inside the main() method, we can use the println() method to print a line of text
to the screen
Java Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by Java (will not be
executed).
Java Variables
Variables are containers for storing data values.
String - stores text, such as "Hello". String values are surrounded by double
quotes
int - stores integers (whole numbers), without decimals, such as 123 or -
123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded
by single quotes
boolean - stores values with two states: true or false
Final Variables
you can add the final keyword if you don't want others (or yourself) to overwrite
existing values (this will declare the variable as "final" or "constant", which means
unchangeable and read-only)
Display Variables
The println() method is often used to display variables.
Java Identifiers
All Java variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
Primitive data types - includes byte, short, int, long, float, double,
boolean and char
Non-primitive data types - such as String, Arrays and Classes (you will learn
more about these in a later chapter)
Integer types stores whole numbers, positive or negative (such as 123 or -456),
without decimals. Valid types are byte, short, int and long. Which type you should
use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or
more decimals. There are two types: float and double.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the
power of 10
float f1 = 35e3f;double d1 = 12E4d;
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
Java Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Java Strings
Strings are used for storing text.
String Length
A String in Java is actually an object, which contain methods that can perform
certain operations on strings. For example, the length of a string can be found with
the length() method
Example
String txt = "Hello World";
System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"
String Concatenation
The + operator can be used between strings to combine them. This is called
concatenation:
we have added an empty text (" ") to create a space between firstName and
lastName on print.
Example
String firstName = "John";String lastName =
"Doe";System.out.println(firstName + " " + lastName);
You can also use the concat() method to concatenate two strings:
Example
String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));
Special Characters
escape characters
To get more control over the random number, e.g. you only want a random number
between 0 and 100, you can use the following formula:
Example
int randomNum = (int)(Math.random() * 101); // 0 to 100
System.out.println(randomNum);
Java Booleans
Very often, in programming, you will need a data type that can only have one of
two values, like:
YES / NO
ON / OFF
TRUE / FALSE
For this, Java has a boolean data type, which can take the values true or false.
Boolean Expression
A Boolean expression is a Java expression that returns a Boolean value: true or
false.
You can use a comparison operator, such as the greater than (>) operator to find
out if an expression (or a variable) is true
You can use these conditions to perform different actions for different decisions.
The if Statement
Use the if statement to specify a block of Java code to be executed if a condition is
true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:
Example
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
Run example »
Example
int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);
Java Switch
❮ PreviousNext ❯
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need
for more testing.
Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more
readable.
Syntax
while (condition) {
// code block to be executed
}
Syntax
do {
// code block to be executed
}while (condition);
The loop will always be executed at least once, even if the condition is false,
because the code block is executed before the condition is tested.
Java For Loop
When you know exactly how many times you want to loop through a block of code,
use the for loop instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through elements
in an array:
Syntax
for (type variableName : arrayName) {
// code block to be executed
}
The following example outputs all elements in the cars array, using a "for-each"
loop:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
Java Continue
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
We have now declared a variable that holds an array of strings. To insert values to
it, we can use an array literal - place the values in a comma-separated list, inside
curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Example
String[] cars = {"Volvo", "BMW", "Ford",
"Mazda"};System.out.println(cars[0]);// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
Array Length
To find out how many elements an array has, use the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford",
"Mazda"};System.out.println(cars.length);// Outputs 4
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
To create a two-dimensional array, add each array within its own set of curly
braces:
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
System.out.println(x); // Outputs 7
We can also use a for loop inside another for loop to get the elements of a two-
dimensional array (we still have to point to the two indexes):
Example
public class MyClass {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]); }
} }}
1
2
3
4
5
6
7
Java Methods
❮ PreviousNext ❯
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as
functions.
Why use methods? To reuse code: define the code once, and use it many
times.
Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses (). Java provides some pre-defined methods,
such as System.out.println().
Call a Method
To call a method in Java, write the method's name followed by two parentheses ()
and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is
called:
Example
Inside main, call the myMethod() method:
Parameters are specified after the method name, inside the parentheses. You can
add as many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as
parameter. When the method is called, we pass along a first name, which is used
inside the method to print the full name:
Example
public class MyClass {
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}
public static void main(String[] args) {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}// Liam Refsnes// Jenny Refsnes// Anja Refsnes
Run example »
Multiple Parameters
public class MyClass {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}// Liam is 5// Jenny is 8// Anja is 31
Run example »
Note that when you are working with multiple parameters, the method call must
have the same number of arguments as there are parameters, and the arguments
must be passed in the same order.
Return Values
The void keyword, used in the examples above, indicates that the method should
not return a value. If you want the method to return a value, you can use a
primitive data type (such as int, char, etc.) instead of void, and use the return
keyword inside the method:
Example
public class MyClass {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}// Outputs 8 (5 + 3)
Example
public class MyClass { /
/ Create a checkAge() method with an integer variable called age
static void checkAge(int age) {
// If age is less than 18, print "access denied"
if (age < 18) {
System.out.println("Access denied - You are not old enough!");
// If age is greater than 18, print "access granted"
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(20); // Call the checkAge method and pass along an age of 20
}
}// Outputs "Access granted - You are old enough!"
Example
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
Systemout.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
Multiple methods can have the same name as long as the number and/or type of
parameters are different.
Java Scope
In Java, variables are only accessible inside the region they are created. This is
called scope.
Method Scope
Variables declared directly inside a method are available anywhere in the method
following the line of code in which they were declared:
Example
public class MyClass {
public static void main(String[] args) {
// Code here CANNOT use x
Int x = 100;
// Code here can use x
System.out.println(x);
}
}
Run example »
Block Scope
A block of code refers to all of the code between curly braces {}. Variables declared
inside blocks of code are only accessible by the code between the curly braces,
which follows the line in which the variable was declared:
Example
public class MyClass {
public static void main(String[] args) {
// Code here CANNOT use x
{ // This is a block
// Code here CANNOT use x
int x = 100;
// Code here CAN use x
System.out.println(x);
} // The block ends here
// Code here CANNOT use x
}
}
Run example »
A block of code may exist on its own or it can belong to an if, while or for
statement. In the case of for statements, variables declared in the statement itself
are also available inside the block's scope.
Java Recursion
Recursion is the technique of making a function call itself. This technique provides a
way to break complicated problems down into simple problems which are easier to
solve.
Recursion may be a bit difficult to understand. The best way to figure out how it
works is to experiment with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more
complicated. In the following example, recursion is used to add a range of numbers
together by breaking it down into the simple task of adding two numbers:
Example
Use recursion to add all of the numbers up to 10.
public class MyClass {
public static void main(String[] args) {
int result = sum(10);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
}
else {
return 0;
}
}
}
Halting Condition
Just as loops can run into the problem of infinite looping, recursive functions can
run into the problem of infinite recursion. Infinite recursion is when the function
never stops calling itself. Every recursive function should have a halting condition,
which is the condition where the function stops calling itself. In the previous
example, the halting condition is when the parameter k becomes 0.
Example
Use recursion to add all of the numbers between 5 to 10.
public class MyClass {
public static void main(String[] args) {
int result = sum(5, 10);
System.out.println(result);
}
public static int sum(int start, int end) {
if (end > start) {
return end + sum(start, end - 1);
}
else {
return end;
}
}
}
Java - What is OOP?
OOP stands for Object-Oriented Programming.
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of
code. You should extract out the codes that are common for the application, and
place them at a single place and reuse them instead of repeating it.
Look at the following illustration to see the difference between class and objects:
class
Fruit
objects
Apple
Banana
Mango
Another example:
class
Car
objects
Volvo
Audi
Toyota
When the individual objects are created, they inherit all the variables and methods
from the class.
Java Classes/Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes
and methods. For example: in real life, a car is an object. The car has attributes,
such as weight and color, and methods, such as drive and brake.
Create a Class
To create a class, use the keyword class:
MyClass.java
Create a class named "MyClass" with a variable x:
To create an object of MyClass, specify the class name, followed by the object
name, and use the keyword new:
Example
Create an object called "myObj" and print the value of x:
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of MyClass:
Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory/folder:
MyClass.java
OtherClass.java
MyClass.java
public class MyClass {
int x = 5;
}
OtherClass.java
class OtherClass {
public static void main(String[] args) {
MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
}
Car.java
public class Car { public void fullThrottle() { System.out.println("The
car is going as fast as it can!"); } public void speed(int maxSpeed) {
System.out.println("Max speed is: " + maxSpeed); }}
OtherClass.java
class OtherClass { public static void main(String[] args) { Car myCar =
new Car(); // Create a myCar object myCar.fullThrottle(); // Call
the fullThrottle() method myCar.speed(200); // Call the speed()
method }}
Run example »
Example
Create a class called "MyClass" with two attributes: x and y:
Accessing Attributes
You can access attributes by creating an object of the class, and by using the dot
syntax (.):
The following example will create an object of the MyClass class, with the name
myObj. We use the x attribute on the object to print its value:
Example
Create an object called "myObj" and print the value of x:
Modify Attributes
You can also modify attribute values:
Example
Set the value of x to 40:
If you don't want the ability to override existing values, declare the attribute as
final:
Example
public class MyClass {
final int x = 10;
public static void main(String[] args) {
MyClass myObj = new MyClass();
myObj.x = 25; // will generate an error: cannot assign a value to a final
variable
System.out.println(myObj.x);
}
}
Multiple Attributes
You can specify as many attributes as you want:
Example
public class Person {
String fname = "John";
String lname = "Doe";
int age = 24;
public static void main(String[] args) {
Person myObj = new Person();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Age: " + myObj.age);
}
}
In the example above, we created a static method, which means that it can be
accessed without creating an object of the class, unlike public, which can only be
accessed by objects:
Example
An example to demonstrate the differences between static and public methods:
Example explained
1) We created a custom Car class with the class keyword.
3) The fullThrottle() method and the speed() method will print out some text,
when they are called.
4) The speed() method accepts an int parameter called maxSpeed - we will use this
in 8).
5) In order to use the Car class and its methods, we need to create an object of
the Car Class.
6) Then, go to the main() method, which you know by now is a built-in Java
method that runs your program (any code inside main is executed).
7) By using the new keyword we created a Car object with the name myCar.
8) Then, we call the fullThrottle() and speed() methods on the myCar object, and
run the program using the name of the object ( myCar), followed by a dot (.),
followed by the name of the method (fullThrottle(); and speed(200);). Notice
that we add an int parameter of 200 inside the speed() method.
Remember that..
The dot (.) is used to access the object's attributes and methods.
To call a method in Java, write the method name followed by a set of parentheses
(), followed by a semicolon (;).
Java Constructors
A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set
initial values for object attributes:
Example
Create a constructor:
// Create a MyClass classpublic class MyClass { int x; // Create a class
attribute // Create a class constructor for the MyClass class public
MyClass() { x = 5; // Set the initial value for the class attribute x }
public static void main(String[] args) { MyClass myObj = new MyClass(); //
Create an object of class MyClass (This will call the constructor)
System.out.println(myObj.x); // Print the value of x }}// Outputs 5
Note that the constructor name must match the class name, and it cannot have a
return type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial
values for object attributes.
Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.
The following example adds an int y parameter to the constructor. Inside the
constructor we set x to y (x=y). When we call the constructor, we pass a parameter
to the constructor (5), which will set the value of x to 5:
Example
public class MyClass { int x; public MyClass(int y) { x = y; } public
static void main(String[] args) { MyClass myObj = new MyClass(5);
System.out.println(myObj.x); }}// Outputs 5
You can have as many parameters as you want:
Example
public class Car { int modelYear; String modelName; public Car(int year,
String name) { modelYear = year; modelName = name; } public static
void main(String[] args) { Car myCar = new Car(1969, "Mustang");
System.out.println(myCar.modelYear + " " + myCar.modelName); }}// Outputs
1969 Mustang
Modifiers
By now, you are quite familiar with the public keyword that appears in almost all
of our examples:
public class MyClass
The public keyword is an access modifier, meaning that it is used to set the
access level for classes, attributes, methods and constructors.
Access Modifiers
For classes, you can use either public or default:
Non-Access Modifiers
For classes, you can use either final or abstract:
Modifier Description
final Attributes and methods cannot be
overridden/modified
static Attributes and methods belongs to the class,
rather than an object
abstract Can only be used in an abstract class, and can
only be used on methods. The method does not
have a body, for example abstract void run();.
The body is provided by the subclass (inherited
from). You will learn more about inheritance and
abstraction in the Inheritance and Abstraction
chapters
transient Attributes and methods are skipped when
serializing the object containing them
synchronized Methods can only be accessed by one thread at a
time
volatile The value of an attribute is not cached thread-
locally, and is always read from the "main
memory"
Final
If you don't want the ability to override existing attribute values, declare attributes
as final:
Example
public class MyClass { final int x = 10; final double PI = 3.14; public
static void main(String[] args) { MyClass myObj = new MyClass();
myObj.x = 50; // will generate an error: cannot assign a value to a final
variable myObj.PI = 25; // will generate an error: cannot assign a value
to a final variable System.out.println(myObj.x); }}
Abstract
An abstract method belongs to an abstract class, and it does not have a body.
The body is provided by the subclass:
Example
// Code from filename: Person.java// abstract class
abstract class Person { public String fname = "John"; public int age = 24;
public abstract void study(); // abstract method}// Subclass (inherit from
Person)class Student extends Person { public int graduationYear = 2018;
public void study() { // the body of the abstract method is provided here
System.out.println("Studying all day long"); }}// End code from filename:
Person.java// Code from filename: MyClass.javaclass MyClass { public static
void main(String[] args) { // create an object of the Student class (which
inherits attributes and methods from Person) Student myObj = new
Student(); System.out.println("Name: " + myObj.fname);
System.out.println("Age: " + myObj.age); System.out.println("Graduation
Year: " + myObj.graduationYear); myObj.study(); // call abstract method
}}
Name: John
Age: 24
Graduation Year: 2018
Studying all day long
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden
from users. To achieve this, you must:
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name of
the variable, with the first letter in upper case:
Example
public class Person { private String name; // private = restricted access
// Getter public String getName() { return name; } // Setter public
void setName(String newName) { this.name = newName; }}
Example explained
The get method returns the value of the variable name.
The set method takes a parameter (newName) and assigns it to the name variable.
The this keyword is used to refer to the current object.
Example
public class MyClass { public static void main(String[] args) { Person
myObj = new Person(); myObj.name = "John"; // error
System.out.println(myObj.name); // error }
If the variable was declared as public, we would expect the following output:
John
Instead, we use the getName() and setName() methods to acccess and update the
variable:
Example
public class MyClass { public static void main(String[] args) { Person
myObj = new Person(); myObj.setName("John"); // Set the value of the name
variable to "John" System.out.println(myObj.getName()); }}// Outputs
"John"
Why Encapsulation?
Better control of class attributes and methods
Class attributes can be made read-only (if you only use the get method), or
write-only (if you only use the set method)
Flexible: the programmer can change one part of the code without affecting
other parts
Increased security of data
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the
Java Development Environment.
The library is divided into packages and classes. Meaning you can either import a
single class (along with its methods and attributes), or a whole package that
contain all the classes that belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:
Syntax
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used
to get user input, write the following code:
Example
import java.util.Scanner;
To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use the
nextLine() method, which is used to read a complete line:
Example
Using the Scanner class to get user input:
Import a Package
There are many packages to choose from. In the previous example, we used the
Scanner class from the java.util package. This package also contains date and
time facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign ( *). The
following example will import ALL the classes in the java.util package:
Example
import java.util.*;
User-defined Packages
To create your own package, you need to understand that Java uses a file system
directory to store them. Just like folders on your computer:
Example
└── root └── mypack └── MyPackageClass.java
MyPackageClass.java
package mypack;class MyPackageClass { public static void main(String[] args)
{ System.out.println("This is my package!"); }}
The -d keyword specifies the destination for where to save the class file. You can
use any directory name, like c:/user (windows), or, if you want to keep the package
within the same directory, you can use the dot sign " .", like in the example above.
Note: The package name should be written in lower case to avoid conflict with class
names.
When we compiled the package in the example above, a new folder was created,
called "mypack".
In the example below, the Car class (subclass) inherits the attributes and methods
from the Vehicle class (superclass):
Example
class Vehicle { protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!"); }}class Car extends Vehicle { private
String modelName = "Mustang"; // Car attribute public static void
main(String[] args) { // Create a myCar object Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk(); // Display the value of the brand attribute (from the
Vehicle class) and the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName); }}
We set the brand attribute in Vehicle to a protected access modifier. If it was set
to private, the Car class would not be able to access it.
Like we specified in the previous chapter; Inheritance lets us inherit attributes and
methods from another class. Polymorphism uses those methods to perform
different tasks. This allows us to perform a single action in different ways.
For example, think of a superclass called Animal that has a method called
animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they
also have their own implementation of an animal sound (the pig oinks, and the cat
meows, etc.):
Remember from the Inheritance that we use the extends keyword to inherit from a
class.
Now we can create Pig and Dog objects and call the animalSound() method on both
of them:
Example
class Animal { public void animalSound() { System.out.println("The animal
makes a sound"); }}class Pig extends Animal { public void animalSound() {
System.out.println("The pig says: wee wee"); }}class Dog extends Animal {
public void animalSound() { System.out.println("The dog says: bow wow");
}}class MyMainClass { public static void main(String[] args) { Animal
myAnimal = new Animal(); // Create a Animal object Animal myPig = new
Pig(); // Create a Pig object Animal myDog = new Dog(); // Create a Dog
object myAnimal.animalSound(); myPig.animalSound();
myDog.animalSound(); }}
To access the inner class, create an object of the outer class, and then create an
object of the inner class:
Example
class OuterClass { int x = 10; class InnerClass { int y = 5; }}public
class MyMainClass { public static void main(String[] args) { OuterClass
myOuter = new OuterClass(); OuterClass.InnerClass myInner = myOuter.new
InnerClass(); System.out.println(myInner.y + myOuter.x); }}// Outputs 15
(5 + 10)
Example
class OuterClass { int x = 10; private class InnerClass { int y = 5;
}}public class MyMainClass { public static void main(String[] args) {
OuterClass myOuter = new OuterClass(); OuterClass.InnerClass myInner =
myOuter.new InnerClass(); System.out.println(myInner.y + myOuter.x); }}
If you try to access a private inner class from an outside class (MyMainClass), an
error occurs:
MyMainClass.java:12: error: OuterClass.InnerClass has private access in
OuterClass
OuterClass.InnerClass myInner = myOuter.new InnerClass();
^
Example
class OuterClass { int x = 10; static class InnerClass { int y = 5;
}}public class MyMainClass { public static void main(String[] args) {
OuterClass.InnerClass myInner = new OuterClass.InnerClass();
System.out.println(myInner.y); }}// Outputs 5
Note: just like static attributes and methods, a static inner class does not have
access to members of the outer class.
Example
class OuterClass { int x = 10; class InnerClass { public int
myInnerMethod() { return x; } }}public class MyMainClass { public
static void main(String[] args) { OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.myInnerMethod()); }}// Outputs 10
Run example »
Run example »
Run example »