What is a class? A class is simply a blueprint or a template for an object.
//sample class
public class X{
private int num;
public X(){}
//Methods go here
}
This is a constructor - it is identical in syntax to a method but it lacks a return type and the name is the same as the class name. They usually take in parameters.
The first part is an instance variable - private int num
. An instance variable is a variable specific to a class and its object. Each object has its own instance variable - assuming the class has an instance variable. If an instance variable isn't assigned a value, it automatically assumes a "zeroish" value: an int and double are equals to 0, strings are "", booleans are false, and objects are null. Note that any other non-instance variable isn't assigned a zeroish value:
int x;
x = 0; //NEVER DO THIS (SPLITTING UP THE VARIABLE AND ASSIGNING OF VALUE)! YOU WILL GET ERRORS!
Instance variables are usually private. The "private" indicates that no other object or external (from another class) method can access it. Why are instance variables private? You wouldn't want someone giving bad input. For example, imagine what would happen if you set num to a string or boolean? That would cause a major error in the compiler. By making an instance variable private, the user has to go through methods to set the instance variables, and these methods can check to make sure the instance variable is set up correctly. You can access an instance variable within its own class however. Just use the syntax this.instanceVariableName
to avoid confusion with other method variables that have the same name.
If you really wanted to, you could make an instance variable public. Don't worry about protected instance variables.
There are 3 types of methods involving instance variables:
Methods are specific to a class.
You call a method using dot notation: ObjectName.runMethod();
Given the following class:
public class Dog {
//instance variables
private int size;
private String breed;
//Constructor
public Dog(int size, String breed) {
this.size = size;
this.breed = breed;
//using "this." notation tells Java to look at the instance variables not the parameters
//but if your instance variables and parameters have different names then "this." is optional
}
//Methods
public void bark() {
System.out.println("woof!");
}
public void setSize(int newSize) {
size = newSize;
}
public int getSize() {
return size;
}
public void changeSize(int s){
size+=s;//same as size = size + s; you could also do size-=s, size*=s, size/=s
}
}
Dog d = new Dog(10, "beagle");
d.bark();
d.setSize(20);
System.out.println(d.getSize());//prints 20
Classes can extend or contain other classes.
For example, let us take the Dog class. (Assume the Animal class is created already)
public class Dog extends Animal{
The extends keyword states Dog IS-A Animal. A class can't extend multiple classes because if you had two parent classes with the same methods, Java has no idea which method you want to call. It also means that Dog can access animal methods but doesn't have access to Animal instance variables directly. However, the converse isn't true. Animal cannot access Dog methods or instance variables. After all, all Dogs are Animals, but not all Animals are Dogs. The Parent class is the class that is being extended; the child class is the one extending itself. Here, Animal is the parent class while Dog is the child class.
Dog IS-A Animal. Cat IS-A Animal. Bird IS-A Animal.
The HAS-A relationship is usually an instance variables. For example, the class SpaceShuttle might have an Engine object. Thus, the SpaceShuttle HAS-A Engine.
Assume that the SpaceShuttle class extends Spaceship class and assume that the blastOff method is only available in the SpaceShuttle class:
SpaceShuttle s = new SpaceShuttle();//valid SpaceShuttle IS-A SpaceShuttle
SpaceShip n = new SpaceShuttle(); //valid SpaceShuttle IS-A SpaceShip
SpaceShuttle x = new SpaceShip();//invalid SpaceShip IS-NOT-A SpaceShuttle always
s.blastOff();//works
n.blastOff();//doesn't work
For line 2, SpaceShip n is restricted to SpaceShip methods only, but if some of those methods are overrode (see next section), Java must look for those methods in the SpaceShuttle class. So the object type (the part before the equal sign) indicates which methods can be called while the instantiated part indicates where to start looking for the method.
Overriding - when a child class copies the same method from its parent class but alters the code within the method
Overloading - when multiple methods have the same name but have different parameters
An example of overloading:
public int run(){
//implementation not shown
}
public int run(int distance){
//implementation not shown
}
These methods are valid as the parameters are different types and the amount of parameters are unique. The parameter variable name is irrelevant. However, two methods with different return types but identical parameters are invalid because Java has no idea which method you are calling. You can overload a constructor. Use super(parametersGoHere)
to call super class's constructor to fill in instance variables.
An example of overriding:
public class A{
public int doSomething(){return 5;}
}
public class B extends A{
public int doSomething(){return 4;}
}
Class B extends A, and both classes have the doSomething() method. However, if you were to instantiate a B object and call the doSomething() method, it would return 4 not 5. If you wanted to call A's method in the B class, you would have to use super.doSomething() which returns 5.
For loops iterate over a fixed length, repeating the same code different times. There are two types of for loops - a regular for loop and a for-each loop.
Regular for loop example:
for(int i = 0; i < 10; i++){
System.out.println(i);
}
The int i = 0 is declaration of the iterator variable. This variable determines how long it will iterate over. The i < 10 is a boolean condition which prevents the loop from going forever. The i++ increments the i variable so the loop isn't stuck at one point. The semicolons separate each expression from another. The loop here prints out i on every line.
The following flow chart shows the logic of the for loop. The moment the boolean condition is false, the loops breaks out of it.
Enhanced For Loop:
for(Object x : Array)
{
}
The for loop iterates over an iterable data structure - such as an array - this will be covered later.
While loops run continuously until the given condition is false.
while(booleanCondition){
//code does something
}
While loops are useful if you don't know how long you have to run the loop. However, a poorly constructed while loop can lead to an infinite loop which can crash a program.
How a regular for loop works
An abstract class is a class that can't be instantiated. Rather, it is a sort of a blueprint for a class. Abstract classes have abstract methods - methods that each subclass extending the abstract class must implement, but it may have variables and methods that don't need to be re-implemented (eg. you don't have write code for that method). Abstract methods are defined as methods that begin with public abstract and have no body code within them. You can only extend one abstract class at a time.
public abstract class Vehicle{
private int size;
private String type;
public Vehicle(int s, String t){
size = s;
type =t;
}
public abstract void run(); // abstract method must be implemented in subclass
public int getSize(){
return size;
}
}
public class Car extends Vehicle{...}
Interfaces are similar to abstract class except they have no constructors or even instance variables and all methods are abstract - which means that all methods must be implemented in subclass. You can implement multiple interfaces.
public interface Honda{
public abstract String brand();
public abstract int findPrice();
}
public class Car extends Vehicle implements Honda{...}
You can't instantiate an interface or an abstract class - they are abstract not concrete:
Car c = new Car(); //valid
Vehicle v = new Car() //valid
Honda h = new Car();// valid
Honda x = new Honda();//doesn't work
Vehicle vh = new Vehicle(1,"Car")//doesn't work
The first 3 statements work because you are calling the constructor of a concrete class (Car) and storing it in a type that is the superclass or class of Car. However, try creating an object of an interface you get an error:
error: Vehicle is abstract; cannot be instantiated
error: Honda is abstract; cannot be instantiated
Abstract classes and interfaces aren't meant to be instantiated - they are meant to be bases or foundations for subclasses.
The following concepts aren't tested by College Board on the AP exam, but they are extremely helpful on the free response section. However, if you don't know how to use them, then don't! If you use them incorrectly, you will still get points off!
break
is a keyword inserted into a loop that exits out of the current loop.
continue
is a keyword that skips the current iteration of the loop and goes onto the next iteration.
Example of break and continue:
for(int i = 0; i < 10; i++){
if(i == 9){
break;
}
if(i == 4){
continue;
}
System.out.println(i);
}
System.out.println("Success");
Console:
0
1
2
3 //skips 4
5
6
7
8
When i
reaches 9, the program will exit the for loop and execute whatever comes after the loop; in this case, the program will print out "Success". When i reaches 4, the program will not execute System.out.println(i)
and goes straight to i = 5
. Breaks are useful to end long loops early.
Note: a break will exit all nested for loops. For example, if you had 3 nested for loops and you inserted a break in the innermost loop, Java will exit all those loops and execute the code that is outside of the outermost loop.
Answer the questions in the Google form below to get feedback on solving real AP questions.