Java OCAJP
By Mikhail Niedre
The Java programming language defines the following kinds of variables:
public class InstanceVariables {
private int i;
public void print() { System.out.println(i); }
public static void main(String[] args) {
new InstanceVariables().print(); // 0
}
}
class Employee{
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development";
}
public int wrongLocalInit(int p) {
int i; // right way: // int i = 0;
if (p < 5)
i += 5; // The local variable i may not have been initialized
return i;
}
шаблон
объекта, а объект - это экземпляр
класса.class
.main()
..
.new
.new
.Box obj; //объявление ссылки на объект
// obj = null;
obj = new Box(); // резервирование памяти для объекта
// и присвоение переменной obj ссылки на этот объект
// Box() - конструктор класса Box
public static void main(String[] argv) {
int a, b, c; // declares three ints, a, b, and c. int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 2; // initializes z. double pi = 3.14; // declares an approximation of pi. char x = 'x'; // the variable x has the value 'x'.
}
Declare, instantiate, initialize and use:
List arr = ArrayList();
arr.size();
arr.contains(100);
arr.remove("asd");
что
он должен делать, но не то как
он это будет делать.implements
), но не могут наследовать классы.extends
), но реализовывать множество интерфейсов (implements
).interface Shape {
void Draw(); // public by default
}
class Circle implements Shape {
void Draw() {// Error: by default method not public
// Cannot reduce the visibility of the inherited method from Shape
System.out.println("Drawing Circle here");
}
}
public interface CarConstants {
static final String ENGINE = "mechanical"; // public by default
static public final String WHEEL = "round";
}
interface IBox {
public void setSize(int size);
}
public class Rectangle implements IBox {
private int size;
public void setSize(int size) { this.size = size; }
public static void main(String[] args) {
// myBox contains the methods/fields ONLY from IBox
IBox myBox = new Rectangle(); myBox.setSize(10);
}
}
abstract
.new
.abstract
.throws
перечисляет типы исключений, которые метод может передавать.import java.io.IOException;
import java.text.ParseException;
public class ThrowsExceptionExample {
public static void main(String[] args) throws IOException,
ParseException {
}
}
throws
.public class ThrowExceptionExample {
public static void main(String[] args) {
//throw new Exception(); // Error: Unhandled exception type Exception
}
}
public class AccountExceptionExample {
public void withdraw() throws Exception {
// no errors
}
public static void main(String[] args)
throws Exception {
new AccountExceptionExample().withdraw();
}
}
Throwable
.Exceptions
, от которой происходят все пользовательские исключения и Error
.Exception
подкласс RuntimeException
исключения являются непроверяемыми и автоматически определяются для программ.Error
обычно возникают в следствие катастрофических сбоев, которые не могут быть обработаны программой.The Java programming language defines the following kinds of variables:
public class Variables {
private int instance_var = 1; //instance variable
public static int CLASS_VAR = 2; //class variable
public void method(String[] parameters) { //parameter int local_var = 3; //local variable }
}
A local variable shadows an instance variable.
class TwoScopes {
int a = 10;
public TwoScopes() {
int a = 5; // hiding (shadowing)
System.out.println(a); // 5
System.out.println(this.a); // 10
}
}
public class TwoScopesExamples {
public static void main(String[] args) {
new TwoScopes();
}
}
Instance variable shadows the inherited variable from it's parent classes.
class Base {
public String greeting = "Hello";
}
class Sub extends Base {
public String greeting = "Good Bye"; // hiding the inherited version
public String getGreeting() { return greeting; }
}
public class VariableOverridingTest {
public static void main(String[] args) {
Base obj = new Sub(); System.out.println(obj.greeting); // "Hello"
obj.greeting = "How are you";
System.out.println(obj.greeting); // "How are you"
System.out.println(obj.getGreeting()); // "Good Bye"
}
}
An array is a container object that holds a fixed number of values of a single type
// declares an array of integers
int[] anArray;
// this form is discouraged
float anArrayOfFloats[];
// will be created an eleven objects
String[] s = new String[10];
The length of an array is established when the array is created. After creation, its length is fixed.
// allocates memory for 10 integers
int[] anArray = new int[10];
// Note that arrays have a length
// field not a length() method.
for(int j = 0; j < anArray.length; j++) {
anArray[j] = j;
}
Each element in an array is accessed by its numerical index.
int i = 0;
long j = 0;
String s[] = { "a", "b", "c", "d" }
String c1[] = s[i]; // ok
String c2[] = s[j]; // compile error!
Data Type | Default Value (for fields) |
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | '\u0000' |
String (or any object) | null |
boolean | false |
class Base {
public String greeting = "Hello";
public String getGreeting() { return greeting; }
}
class Sub extends Base {
// greeting (Base)
public String greeting = "Good Bye"; // greeting (Sub)
@Override
public String getGreeting() { return greeting;
// return super.greeting; // hidded
}
}
public class VariableOverridingTest {
public static void main(String[] args) {
Base obj1 = new Base();
Base obj2 = new Sub();
System.out.println(obj1.getGreeting()); // "Hello"
System.out.println(obj2.getGreeting()); // "Good Bye"
}
}
If a few methods of an one class have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.
public class Shape {
/** display Square area */
static void displayArea(int a) {
System.out.println(a*a);
}
/** display Triangle area */
static void displayArea(int b, int h) {
System.out.println((b*h)/2);
}
public static void main(String[] args) {
int a = 3, b = 4, c = 5;
displayArea(a);
displayArea(b, c);
}
}
Method overloading is one of the ways that Java implements polymorphism.
public class OverloadingExample {
public static void print(Object foo) {
System.out.println("Object");
}
public static void print(Integer foo) {
System.out.println("Integer");
}
public static void main(String[] args) {
Object foo = new Integer(42);
print(foo);
Object bar = new Object();
print(bar);
}
}
When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call.
public class OverloadingExample {
public static void main(String[] args) {
print("asd");
print(10);
}
public static void print(int i) {
System.out.println("int: " + i);
}
public static void print(String s) {
System.out.println("String: " + s);
}
}
You can have two methods with the same arguments and different return types only if one of the methods is inherited and the return types are compatible.
class A {
Object foo() { System.out.println("A.foo()");
return new Object();
}
}
class B extends A {
String foo() { System.out.println("B.foo()");
return new String();
}
}
public class OverloadingExample2 {
public static void main(String[] args) {
Object foo1 = new A().foo();
Object foo2 = new B().foo();
}
}
A difference in return type only is not sufficient to constitute an overload and is illegal.
public class OverloadingExample3 {
private static int sum = 0;
public static void main(String[] args) {
System.out.println(sum(1,2));
}
public static int sum(int i, int j) {
return (i + j);
}
public static void sum(int i, int j) {
sum = i + j;
}
}
Overloaded methods may call one another simply by providing a normal method call with an appropriately formed argument list.
public class OverloadingExample7 {
public static void main(String[] args) {
Object a = "asd"; print(a);
a = 12; print(a);
}
public static void print(Object o) {
if (o instanceof String) print((String) o);
if (o instanceof Integer) print((Integer) o);
}
private static void print(String s) {
System.out.println("String: " + s);
}
private static void print(Integer i) {
System.out.println("Integer: " + i);
}
}