How do you start to learn Java or Object Oriented Programming (OOP)? I had an excellent teacher who cared about doing things the right way and teaching us why things worked the way that they did. Below are some of my crib notes from my first class with him.
EXERCISE ONE: Describe a Car to an Alien
Characteristics – Things a Car Has
Wheels, brakes, fuel, lights, signals, models, transmission
Behaviors (Methods) – Things a Car Can Do
Move, turn, stop, accelerate
EXERCISE TWO: Look Around for Groups of Things in the Room
GROUP 1: Human Beings (13) in this Room
Characteristics: Hair color, height, weight, eye color, gender, age
GROUP 2: Monitors
GROUP 3: Seats
We know these because of their characteristics. Humans easily recognize characteristics by instinct. Before OOP, languages were artificial. With OOP, they recognized that we should model programs around objects, like humans do naturally. Then, other people can reuse those objects
Students that have worked in other languages will have more problems than those who are starting fresh. Don’t try to fit Java into a C++ paradigm. First, design what you are going to do in an object-oriented way. You can’t write Java objects, instead you write Java classes. When you hear the word car, you immediately have a mental picture of a car and a list of related characteristics.
Hierarchy of Objects
Transportation – Super-Class
Ground Transportation – Sub-Class
Human Beings – Super-Class
Male, Female – Sub-Class
Can model an abstraction of a car for your purposes. Hertz would view the car differently from Lexus or a car mechanic. That’s because different people will come out with different interpretations. Hertz isn’t interested in engines but the car mechanic does. Hertz is interested in rental rates, insurance, etc.
We have to be able to abstract the item into a model. What are the objects involved in a payroll? How can we turn a class into an object?
Instantiate it. Create an image of the class. The class is the cookie-cutter used to create objects.
Car Characteristics
Wheels = 4
Brakes = yes
Fuel = gas
Lights = halogen
Signals = Yes
Model = Lexus
Transmission = Manual
My Auto
Make = Mazda
Model = 5
Year = 2006
Color = Red
We tell objects apart by their characteristics, but they are members of the same class. Isolate those things that make it different.
- Things that are the same = Goes back, goes right, brakes
- Things that are different = Make, model, color
If you are looking for a motorcycle, you ignore all the cars.
In Java, you have to write classes. Everything is a class. Use the classes to create an object and then you use that object inside your program.
Classes Have 2 Things:
- Characteristics
- Behaviors
Has an argument list, a return type – But it has to belong to a class.
Airplane.stop();
Bike.move();
Airplane move function is different from a boat or a bike. Behaviors are tied to a particular object.
View a Java application as a group of objects. If they don’t interact, they are useless. Java application is a set of interacting Java objects that pass message to each other.
Fuel Injector |
|||
Car1 |
|||
Mechanic |
Car1.start();
In order to start, it has to do a number of things. For example, the car calls the fuel injector which then reports back.
To us, we turn a key and it starts. Under the hood, a number of objects are interacting. Nice thing about OOP, those objects exist. You just use them. Don’t need to know anything besides how to start the car with the key.
Garage door opener has a button that you hit. It also has methods like open, close, jam.
Pick the right objects, then give it a behavior that you know it can do.
These objects need to be created. Go into a clothes store and want to buy a jacket. Walk over to jackets because he understands the jacket class. From there, create your jacket object by picking through the available objects.
Size = 40
Color = Black
Price = $$
Have a closet full of classes. Type is virtually interchangeable with class.
Class is the blueprint. Object is the house.
- Can’t live in a blueprint, but you can live in a house built with a blueprint.
Class is the recipe. Object is the cake.
Take things on faith. Catch-22 – where we need to practice code but we won’t be able to understand until later.
Java gives you 3 things
1) Java Compiler (javac) – Complies text files into a form that Java understands, will not produce output if there is an error in the code. Java is tough on developers. When you compile, it puts it into bytecode. Can write on Windows and run on a Mac. Write once, run anywhere.
2) Java Virtual Machine (java) – Just a computer program that runs Java code. This will vary according to the platform. A Windows JVM is different from a Mac JVM.
3) Java Class Library – 5000+ Classes. That’s all there is – just Java classes. But you can take any of these classes and turn it into an object and use all of the functions built into that class.
What can you do with a String? An Array?
Java wrote 5000 classes that allow you to do lots of things, but you’ll probably just use 20 in this class and 100 in your everyday work. Reading from a database – class for that. Read from keyboard – class for that. Browse the internet – class for that.
JAVA SYNTAX. Syntax is similar to C. Hard part is the object-oriented design. That’s why you’ll need to get experience in.
OTHER PEOPLE’S CLASSES. With Java, you don’t have to reinvent the wheel. Only have to write those pieces specific to your application. Don’t need the source code. You can reuse the classes that are already out there.
Integrated Development Environment (IDE) – Eclipse and NetBeans are the most common. We’ll be using a text editor with these exercises.
Plain ASCII text
xxxx.java
- Has to be saved with the .java suffix
- One file contains one class
- Fifty classes, fifty files
- Name of the class has to match the name of the file
- Case sensitive (car != Car)
Javac <filename.java>
C:>javac
Usage: javac <options> <source files>
where possible options include:
-g Generate all debugging info
-g:none Generate no debugging info
-g:{lines,vars,source} Generate only some debugging info
-nowarn Generate no warnings
-verbose Output messages about what the compiler is doing
-deprecation Output source locations where deprecated APIs are used
-classpath <path> Specify where to find user class files and annotation processors
-cp <path> Specify where to find user class files and annotation processors
-sourcepath <path> Specify where to find input source files
-bootclasspath <path> Override location of bootstrap class files
-extdirs <dirs> Override location of installed extensions
-endorseddirs <dirs> Override location of endorsed standards path
-proc:{none,only} Control whether annotation processing and/or compilation is done.
-processor <class1>[,<class2>,<class3>…]Names of the annotation processors to run; bypasses default discovery process
-processorpath <path> Specify where to find annotation processors
-d <directory> Specify where to place generated class files
-s <directory> Specify where to place generated source files
-implicit:{none,class} Specify whether or not to generate class files for implicitly referenced files
-encoding <encoding> Specify character encoding used by source files
-source <release> Provide source compatibility with specified release
-target <release> Generate class files for specific VM version
-version Version information
-help Print a synopsis of standard options
-Akey[=value] Options to pass to annotation processors
-X Print a synopsis of nonstandard options
-J<flag> Pass <flag> directly to the runtime system
C:>
Javac will only pick up on compile-time errors. It won’t report on run-time errors. Divide by zero is a run-time error. Java compiler takes your file, looks at all the referenced classes, and makes sure that everything is correct. The class file that it produces is unreadable bytecode.
To run our Java program, we call java. Open up command-line and just use the class name, not the classname.class.
java <classname> (Not java <classname>.class)
To run Java programs, you just need the Java Runtime Environment (JRE).
To create Java programs, you need the Java Developer’s Kit (JDK). This will include the Java complier and Java class library. It is also much larger than the JRE.
Save programs in the following directory
C:javarun
In Windows Explorer, Tools > Folder Options > Uncheck the Hide Extensions for Known File Types
There are 50 reserved Java keywords. They are all lowercase.
FIRST EXERCISE
public class LoveJava {
}
Nothing goes outsides the curly brackets. Only three things go inside the curly brackets
- Instance variables (or characteristics)
- Methods
- Later, we will add constructors
For now, everything will use the default constructor and just have one method.
public static void main (String[] args) {
}
Main is the name of the method
Void is the return type. This must always be defined (integer, float, string) even if it doesn’t return anything.
Static – just type for now
Public means anyone can use this method
() – Arguments that the method expects
Every variable in Java must have a type. A variable is a placeholder for a value. What you store in a variable can one of several numeric types. Whole numbers can be – byte (1 byte), short (2 bytes), int (4 bytes), long (8 bytes). How large do you want your data value to be?
Float (4 bytes) and double (8 bytes) are used for decimal numbers.
(String[] args)
Passing in an array of Strings called args.
Methods are defined in the curly brackets. Turn can be a method. Extra info is passed in as arguments. How do you turn? Left? Right? Smoothly?
System.out.print (Prints and leaves the cursor at the end of the line)
System.out.println (Prints and then adds a new line)
Name of the object + name of the method + argument
System.out.println(“This is Chris.”);
Java is very strict. Every line ends in a semicolon.
To compile, open up the command line and switch to the javarun directory
cd javarun
javac LoveJava.java
To run it, type in
java LoveJava
Java will automatically run the main method, unless another method is specified. But not all classes must have a main method, just the class that you start with. Every other method you can determine but your start-up class has to have a main method exactly like this:
public static void main (String[] args) {
}
SECOND EXERCISE
Working with instance variables
radius; <- This is illegal
double radius;
radius=20.0;
Also, put it within the main method.
For comments
//For a single line
/*
For a multi-line comment
*/
With strings, + concatenates values together.
System.out.println(“The area of a circle of radius ” + radius + ” is ” + area);
Java is smart enough to handle basic data type conversion. It knows to change the behavior of the addition sign and cast the double as a String value.
THIRD EXERCISE
String firstName;
Once you declare a variable, you cannot change the type. Also, you have to assign a value to the variable. When we ran the class, it threw an error because the name was not initialized.
Until now, you’ve been using objects and not realizing it. They are primitive objects
String
double
Outside of the main method, use
public static Scanner myScanner = new Scanner(System.in);
new is how we create objects in Java. Here, we created an object called myScanner with a type of Scanner. Assign it to a new object by calling new Scanner and telling the Scanner what we want to scan. This class can read from a file or a keyboard. System.in means standard input, which means the keyboard. System.out means the screen.
double x = 6.0;
public static Scanner myScanner = new Scanner(System.in);
In our earlier exercises, we defined the instance variable and then assigned it later. We can also define and assign it on the same line.
Documentation on Classes
Within the JDK, you can look up the Scanner object here.