Object-Oriented Programming in Java
Similarities with C++
User-defined classes can be used like built-in types.
Basic syntax
Differences from C++
Methods (member functions) are the only function type
Object is the topmost ancestor for all classes
All methods use the run-time, not compiletime, types
(i.e. all Java methods are like C++ virtual functions)
The types of all objects are known at run-time
All objects are allocated on the heap (always
safe to return objects from methods)
Single inheritance only
Java 8 has multiple inheritance (as we will
see), but via interfaces not by normal classes,
so is a bit of a nonstandard variation of
multiple inheritance
Object-Oriented Nomenclature
Class means a category of things
A class name can be used in Java as the type of a field or
local variable or as the return type of a function (method)
There are also fancy uses with generic types such as
List<String>. This is covered later.
Object means a particular item that
belongs to a class
Also called an instance
Example
String s1 = "HelloWorld";
Here, String is the class, and the variable s1 and the value
"HelloWorld" are objects (or instances of the String class)
public class Car { (In MyProgram.java)
public double x, y, speed, direction;
public String name;
}
public class Test1 {
(In Test1.java)
public static void main(String[] args) {
Car c1 = new Car();
c1.x = 0.0;
c1.y = 0.0;
c1.speed = 1.0;
c1.direction = 0.0;
// East
c1.name = MyCar";
Car c2 = new Car();
c2.x = 0.0;
c2.y = 0.0;
c2.speed = 2.0;
c.direction = 135.0; // Northwest
c2.name = MyCar2";...
Move the car one step based on their direction and speed.
c1.x = c1.x + c1.speed
* Math.cos(c1.direction * Math.PI / 180.0);
c1.y = c1.y + c1.speed
* Math.sin(s1.direction * Math.PI / 180.0);
c2.x = c2.x + c2.speed
* Math.cos(s2.direction * Math.PI / 180.0);
c2.y = c2.y + c2.speed
* Math.sin(s2.direction * Math.PI / 180.0);
System.out.println(s1.name + " is at ("
+ c1.x + "," + c1.y + ").");
System.out.println(s2.name + " is at ("
+ c2.x + "," + c2.y +
").");
}
}
.
Compiling and running manually (rare)
DOS> javac Test1.java
DOS> java Test1
Output:
C1 is at (1,0).
C2 is at (-1.41421,1.41421).
Important points: Java naming conventions
Format of class definitions
Creating classes with new
Accessing fields with variableName.fieldName
Start classes with uppercase letters
Constructors (discussed later in this section) must exactly match class name, so
they also start with uppercase letters
public class MyClass {
...
}
Start other things with lowercase letters
Instance vars, local vars, methods, parameters to methods
public class MyClass {
public String firstName,lastName;
public String fullName() {
String name = firstName
lastName;
return(name);
}
}
" +