logo资料库

JavaForPythonProgrammers.pdf 英文原版

第1页 / 共37页
第2页 / 共37页
第3页 / 共37页
第4页 / 共37页
第5页 / 共37页
第6页 / 共37页
第7页 / 共37页
第8页 / 共37页
资料共37页,剩余部分请下载后查看
Preface
Introduction
Why Learn another programming Language?
Why Learn Java? Why not C or C++?
Lets look at a Java Program
Java Data Types
Numeric
Import
Declaring Variables
Input / Output / Scanner
String
List
Arrays
Dictionary
Conditionals
Simple if
if else
elif
Loops and Iteration
Definite Loop
Indefinite Loops
Defining Classes in Java
Writing a constructor
Methods or Member Functions
Method Signatures and Overloading
Inheritance
The Object Class
Abstract Classes and Methods
Interfaces
Static member variables
Static Methods
Full Implementation of the Fraction Class
Common Mistakes
Naming Conventions
Java Documentation Online
Colophon
Shameless Plug
Java for Python Programmers Bradley N. Miller January 27, 2008 1
1 Preface Welcome to Java for Python Programmers. This short ebook is an ongoing project to help Computer Science students who have had one or two semesters of Python learn the Java programming language. If you are not a part of that audience you may still find this a useful way to learn about Java. This book is written using the build on what you know philosophy. In order to help you learn Java I will start with a Python example and then implement the example in Java. Along the way we will examine the strengths, weaknesses and differences between those two languages. This book does not attempt to replace the many good Java reference books that are available, in fact I use this in my course along with Horstman’s Core Java volumes. Please feel free to use this book for yourself, or if it fits a class you are teaching you are welcome to use this as a resource for your own class. I have published this article using a Creative Commons license to encourage you to use it, change it, and modify it for your own purposes. I would appreciate knowing what you think if you do use this book, and I would love to see any modifications or additions you make. Brad Miller bmiller@luther.edu January, 2008 This work is licensed under a Creative Commons Attribution 3.0 United States License. See http://creativecommons.org 2
Contents 1 Preface 2 Introduction 3 Why Learn another programming Language? 4 Why Learn Java? Why not C or C++? 4.1 Lets look at a Java Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Java Data Types 5.1 Numeric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.1.1 Import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.1.2 Declaring Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Input / Output / Scanner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.1.3 5.2 String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.3 List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.4 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.5 Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Conditionals 6.1 Simple if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . if else elif . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.3 7 Loops and Iteration 7.1 Definite Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Indefinite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.2 8 Defining Classes in Java 8.1 Writing a constructor 8.2 Methods or Member Functions 8.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2.1 Method Signatures and Overloading . . . . . . . . . . . . . . . . . . . . . . . Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.3.1 The Object Class 8.3.2 Abstract Classes and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . 8.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Interfaces 8.5 Static member variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.6 Static Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.7 Full Implementation of the Fraction Class . . . . . . . . . . . . . . . . . . . . . . . . 9 Common Mistakes 3 2 5 5 6 6 9 9 10 11 12 13 13 16 17 18 18 19 19 21 21 22 23 25 25 26 28 28 29 30 32 32 33 35
10 Naming Conventions 11 Java Documentation Online 12 Colophon 13 Shameless Plug 35 36 36 36 4
2 Introduction This book assumes that you are already familiar with the Python programming language. We will use Python as a starting point for our journey into Java. We will begin by looking at a very simple Java program, just to see what the language looks like and how we get a program to run. Next, we will look at the main constructs that are common to most programming languages: • Data Types • Loops • Reading user input • Conditionals Once we have the basics of Java behind us we will move on to look at the features of Java that are both unique and powerful. • Classes • Interfaces • Collections • Graphical User Interface Programming • Generic Programming Please note that this book is a work in progress. I will continue to update and post new versions. 3 Why Learn another programming Language? Python is a nice language for beginning programming for several reasons. First the syntax is sparse, and clear. Second, the underlying model of how objects and variables work is very consistent. Third, you can write powerful and interesting programs without a lot of work. However, Python is representative of one kind of language, called a dynamic language. You might think of Python as being fairly informal. There are other languages, Like Java and C++ that are more formal. These languages have some advantages of their own. First, is speed: For very large programs Java and C++ are going to give you the best performance. Second is their maintainability. A lot of what makes Python easy to use is that you must remember certain things. For example if you set variable x to reference a turtle, and forget later that x is a turtle but try to invoke a string method on it, you will get an error. Java and C++ protect you by forcing you to be upfront and formal about the kind of object each variable is going to refer to. In one sense Python is representative of a whole class of languages, sometimes referred to as “script- ing languages.” Other languages in the same category as Python are Ruby and Perl. Java is representative of what I will call industrial strength languages. Industrial strength languages are good for projects with several people working on the project where being formal and careful about what you do may impact lots of other people. Languages in this category include C++, C, C# and Ada. Programming languages will always change. As the field of computer science advances there will be new programming languages and you will need to learn them. It is important to learn several programming languages so that you know what to expect. There are certain features that most programming languages have in common; variables, loops, conditionals, functions. And there are some features that are unique. If you know what is common in languages that is a good place to start. 5
4 Why Learn Java? Why not C or C++? • Java is the most widely taught programming language. • Java is more popular • Java is industrial strength used for large systems by large groups of people • If you know Java learning C++ is easy. Java is an enormous language. There are over 3700 different classes included in the Java 6 Standard Edition. We could not begin to scratch the surface of these classes even if we devoted all 2700 minutes of class time that we have in a semester. However Java is very powerful and we will write some very powerful programs this semester. 4.1 Lets look at a Java Program A time honored tradition in Computer Science is to write a program called “hello world.” The “hello world” program is simple and easy. There are no logic errors to make, so getting it to run relies only on understanding the syntax. To be clear lets look a a “complicated” version of hello world for Python: 1 def main (): 2 print " Hello World ! " Remember that we can define this program right at the Python command line and then run it: >>> main() "Hello World!" >>> Now lets look at the same program written in Java: 1 public c l a s s Hello { 2 3 4 5 6 7 } } public s t a t i c void main ( String [] args ) { System . out . println ( " Hello World ! " ); What we see is that at the core there are a few similarities, such as a main and the string “Hello World” However there is a lot more stuff around the edges that make it harder to see the core of the program. Do not worry! An important skill for a computer scientist is to learn what to ignore and what to look at carefully. You will soon find that there are some elements of Java that will fade into the background as you become used to seeing them. One thing that will help you is to learn a little bit about Java Naming Conventions. The first question you probably have about this little program is “How do I run it?” Running a Java program is not as simple as running a Python program. The first thing you need to do with a Java program is compile it. The first big difference between Java and Python is that Python is an interpreted language. We could run our Python programs in the Python interpreter and we were quite happy to do that. Java makes running programs a two step process. First we must type the hello world program into a file and save that file using the name Hello.java The file name must be the same as the public class you define in the file. Once we have saved the file we compile it from the command line as follows: 6
$ javac Hello.java $ ls -l Hello.* -rw-r--r-- -rw-r--r-- 1 bmiller bmiller 1 bmiller bmiller 391 Jul 19 17:47 Hello.class 117 Jul 19 17:46 Hello.java The command javac compiles our java source code into compiled byte code and saves it in a file called Hello.class. Hello.class is a binary file so you won’t learn much if you try to examine the class file with an editor. Hopefully you didn’t make any mistakes, but if you did you may want to consult the Common Mistakes section for helpful hints on compiler errors. Now that we have compiled our java source code we can run the compiled code using the java command. $ java Hello Hello World! $ Now you may be wondering what good is that extra step? What does compiling do for us? There are a couple of important benefits we get from compiling: • Early detection of errors • Faster Program Execution The job of the compiler is to turn your java code into language that the Java Virtual Machine (JVM) can understand. We call the code that the JVM understands byte code. The JVM interprets the byte code much like the Python interpreter interprets your Python. However since byte code is much closer to the native language of the computer it can run faster. When the compiler does the translation it can find many different kinds of errors. For example if you make a typo the compiler will find the typo and point it out to you before you ever run the program. We will look at some examples of compiler errors shortly. Chances are you will create some on your own very soon too. Now that we have run our hello world program, lets go back and look at it carefully to see what we can learn about the Java language. This simple example illustrates a few very important rules: 1. Every Java program must define a class, all code is inside a class. 2. Everything in Java must have a type 3. Every Java program must have a function called public static void main(String[] args) Lets take the hello world example a line at a time to see how these rules are applied. On line 1 we see that we are declaring a class called Hello. As rule 1 says all Java code resides inside a class. Unlike Python where a program can simply be a bunch of statements in a file, Java programs must be inside a class. So, we define a class, Hello is not a very useful class it has no instance variables, and only one method. You will also notice the curly brace { In Java blocks of code are identified by pairs of curly braces. The block starts with a { and ends with a }. You will notice that I indented my code that followed the left brace, but in Java this is only done by convention it is not enforced. On the next line we start our method definition. The name of this method is: public static void main(String[] args)! Everything on this line is significant, and helps in the identification of this method. For example the following lines look similar but are in fact treated by Java as completely different methods: 7
• public void main(String[] args) • public static void main(String args) • public static void main() • void main(String args) Just digging in to this one line will take us deep into the world of Java, so we are going to start digging but we are not going to dig too deeply right away. Much of what could be revealed by this one line is better understood through other examples, so be patient. The first word, public indicates to the Java compiler that this is a method that anyone can call. We will see that Java enforces several levels of security on the methods we write, including public, protected, and private methods. The next word, static tells Java that this is a method that is part of the class, but is not a method for any one instance of the class. The kind of methods we typically wrote in Python required an instance in order for the method to be called. With a static method, the object to the left of the . is a class, not an instance of the class. For example the way that we would call the main method directly is: Hello.main(parameter1). For now you can think of static methods the same way you think of methods in Python modules that don’t require an instance, for example the math module contains many methods: sin, cos, etc. You probably evaluated these methods using the names math.cos(90) or math.sin(60). The next word, void tells the Java compiler that the method main will not return a value. This is roughly analogous to omitting the return statement in a Python method. In other words the method will run to completion and exit but will not return a value that you can use in an assignment statement. As we look at other examples we will see that every Python function must tell the compiler what kind of an object it will return. This is in keeping with the rule that says everything in Java must have a type. In this case we use the special type called void which means no type. Next we have the proper name for the method: main. The rules for names in Java are similar to the rules in Python. Names can include letters, numbers, and the _. Names in Java must start with a letter. Finally we have the parameter list for the method. In this example we have one parameter. The name of the parameter is args however, because everything in Java must have a type we also have to tell the compiler that the value of args is an array of strings. For the moment You can just think of an array as being the same thing as a list in Python. The practical benefit of declaring that the method main must accept one parameter and the parameter must be a an array of strings is that if you call main somewhere else in your code and and pass it an array of integers or even a single string, the compiler will flag it as an error. That is a lot of new material to digest in only a single line of Java. Lets press on and look at the next line: System.out.println("Hello World!");. This line should look a bit more familiar to you. Python and Java both use the dot notation for finding names. In this example we start with System. System is a class. Within the system class we find the object named out. The out object is the standard output stream for this program. Having located the out object Java will now call the method named println(String s) on that object. The println method prints a string and adds a newline character at the end. Anywhere in Python that you used the print function you will use the System.out.println method in Java. Now there is one more character on this line that is significant and that is the ; at the end. In Java the ; signifies the end of a statement. Unlike Python where statements are almost always only one line long java statements can spread across many lines. The compiler knows it has reached the end of a statement when it encounters a ;. This is a very important difference to remember. In Java the following statements are all legal and equivalent. I would not encourage you to write your code like this, but you should know that it is legal. System.out.println("Hello World"); System.out.println("Hello World") 8
分享到:
收藏