Download presentation
Presentation is loading. Please wait.
1
An introduction to Java
15-Jun-18
2
What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand Java is currently a very popular language Java is a large, powerful language but it is not simple! Compared to C++, Java is elegant
3
Declarations, statements, comments
A declaration gives some information to the computer A statement tells the computer to do something Statements should really be called “commands” Comments are ignored by the computer—they are explanations of your program for human beings to read
4
Two aspects of Java Java has syntax and semantics
This is where you begin It is possible to learn everything about Java’s syntax and semantics We will cover most of Java’s syntax and semantics Java also has “packages” Packages are sort of like vocabulary bundles To be good at Java, you need to learn many packages There are more Java packages than you can ever learn
5
The programming cycle ACTIONS: edit compile run (execute) ok ok
logic errors runtime error syntax errors edit compile run (execute) .java file .class file ok results ok input data (optional) You only get one runtime error at a time. Logic errors are not detected by the computer. The longer the arrow, the harder it is to debug. THINGS: ok
6
Vocabulary I JRE, Java Runtime Environment
This is the software that allows you to run Java programs on your computer SDK, System Development Kit (previously called JDK, Java Development Kit) The software that allows you to create and run Java programs on your computer When you install the SDK, you get a JRE along with it IDE, Integrated Development Environment A tool that makes it easier to write programs
7
Vocabulary II Beta software Interface GUI, Graphical User Interface
Software that is new, untested, often buggy Interface the place where things touch each other the way that distinct things communicate GUI, Graphical User Interface A way for the computer and the user to communicate via graphics (pictures) on the screen
8
JBuilder JBuilder is an IDE (Integrated Development Environment). It includes an editor, which you use to write your programs a graphical editor, to easily create GUIs a debugger, to help you find your mistakes an easy way to organize and run Java programs
9
What You Need 256 MB of RAM (512 MB recommended)
800 MHz Pentium III or better Java JDK or 1.5 (includes JRE) JBuilder 2005 Foundation By the way: the SDK and JBuilder Foundation are free
10
Variables A variable is a “box” that holds data
Every variable has a name Examples: name, age, address, isMarried Variables start with a lowercase letter In multiword variables, each new word is capitalized Every variable has a type of value that it can hold For example, name might be a variable that holds a String (sequence of characters) age might be a variable that holds an integer value isMarried might be a variable that holds a boolean (true or false) value
11
Some Java data types In Java, the four most important primitive (simple) types are: int variables hold integer values double variables hold floating-point numbers, that is, numbers containing a decimal point boolean variables hold a true or false value char variables hold single characters Another important type is the String A String is an Object, not a primitive type A String is composed of zero or more chars
12
Declaring variables Every variable that you use in a program must be declared (in a declaration) The declaration specifies the type of the variable The declaration may give the variable an initial value Examples: int age; int count = 0; double distance = 37.95; boolean isReadOnly = true; String greeting = "Welcome to CIT 591"; String outputLine;
13
Assignment statements
Values can be assigned to variables by assignment statements The syntax is: variable = expression; The expression must be of the same type as the variable The expression may be a simple value or it may involve computation Examples: name = "Dave"; count = count + 1; area = (4.0 / 3.0) * * radius * radius; isReadOnly = false; When a variable is assigned a value, the old value is discarded and totally forgotten
14
Comments There are three kinds of comments:
A comment is a note to any human reading the program; comments are ignored by Java There are three kinds of comments: // starts a comment that goes to the end of the line /* starts a comment that can extend over many lines, and ends at */ /** is a “javadoc” comment that can be extracted from your program and used in documentation */ A comment may be put after a statement (on the same line) to say something about that one statement A comment may be put before a statement, to say something about the following statements Example: // Swap the values of x and y temp = x; // save old value of x in temp x = y; // replace old value of x with y y = temp; // this many comments is just silly
15
Methods A method is a named group of declarations and statements
void tellWhatYearItIs( ) { int year = 2004; System.out.println("Hello in " + year + "!"); } We “call,” or “invoke” a method by naming it in a statement: tellWhatYearItIs( ); This should print out Hello in 2004!
16
Arithmetic expressions
Arithmetic expressions may contain: + to indicate addition - to indicate subtraction * to indicate multiplication / to indicate division % to indicate remainder of a division (integers only) parentheses ( ) to indicate the order in which to do things An operation involving two ints results in an int When dividing one int by another, the fractional part of the result is thrown away: 14 / 5 gives 2 Any operation involving a double results in a double: gives 4.7
17
if statements An if statement lets you choose whether or not to execute one statement, based on a boolean condition Syntax: if (boolean_condition) statement; Example: if (x < 100) x = x + 1; // adds 1 to x, but only if x is less than 100 C programmers take note: The condition must be boolean An if statement may have an optional else part, to be executed if the boolean condition is false Syntax: if (boolean_condition) statement; else statement; Example: if (x >= 0 && x < limit) y = x / limit; else System.out.println("x is out of range: " + x);
18
Compound statements Multiple statements can be grouped into a single statement by surrounding them with braces, { } Example: if (score > 100) { score = 100; System.out.println("score has been adjusted"); } Unlike other statements, there is no semicolon after a compound statement Braces can also be used around a single statement, or no statements at all (to form an “empty” statement) It is good style to always use braces in the if part and else part of an if statement, even if the surround only a single statement Indentation and spacing should be as shown in the above example
19
while loops A while loop will execute the enclosed statement as long as a boolean condition remains true Syntax: while (boolean_condition) statement; Example: n = 1; while (n < 5) { System.out.println(n + " squared is " + (n * n)); n = n + 1; } Result: squared is squared is squared is squared is 16 C programmers take note: The condition must be boolean Danger: If the condition never becomes false, the loop never exits, and the program never stops
20
Method calls A method call is a request to an object to do something, or to compute a value System.out.print(expression) is a method call; you are asking the System.out object to evaluate and display the expression A method call may be used as a statement Example: System.out.print(2 * pi * radius); Some method calls return a value, and those may be used as part of an expression Example: h = Math.sqrt(a * a + b * b);
21
A complete program public class SquareRoots { // Prints the square roots of numbers 1 to public static void main(String args[]) { int n = 1; while (n <= 10) { System.out.println(n + " " + Math.sqrt(n)); n = n + 1; } } } etc.
22
Classes and Objects A Java program consists of one or more classes
A class is an abstract description of objects Here is an example class: class Dog { ...description of a dog goes here... } Here are some objects of that class:
23
More Objects Here is another example of a class:
class Window { ... } Here are some examples of Windows:
24
Example: a “Rabbit” object
You could create an object representing a rabbit It would have data: How hungry it is How healthy it is Where it is And methods: eat, run, dig, hide
25
Objects have behaviors
In old style programming, you had: data, which was completely passive functions, which could manipulate any data In O-O programming, an object contains both data and methods that manipulate that data An object is active, not passive; it does things An object is responsible for its own data But it can expose that data to other objects
26
Classes A class describes a set of objects
The objects are called instances of the class A class describes: Fields that hold the data for each object Constructors that tell how to create a new object of this class Methods that describe the actions the object can perform In addition, a class can have data and methods of its own (not part of the objects) For example, it can keep a count of the number of objects it has created Such data and methods are called static
27
Defining a class Here is the simplest syntax for defining a class:
class ClassName{ // the fields (variables) of the object // the constructors for the object // the methods of the object } You can put public, protected, or private before the word class Things in a class can be in any order (I recommend the above order)
28
Classes contain data definitions
Classes describe the data held by each of its objects Example: class Dog { String name; int age; rest of the class... } Data usually goes first in a class A class may describe any number of objects Examples: "Fido", 3; "Rover", 5; "Spot", 3; A class may describe a single object, or even no objects at all
29
Defining fields An object’s data is stored in fields (also called instance variables) The fields describe the state of the object Fields are defined with ordinary variable declarations: String name; Double health; int age = 0;
30
Objects have state An object contains data
The data represent the state of the object Data can also describe the relationship of the object to other objects Example: a checkingAccount might have A balance (the internal state of the account) An owner (some object representing a person) An accountNumber (used as an ID number)
31
Classes contain methods
A class may contain methods that describe the behavior of objects Example: class Dog { void bark() { System.out.println("Woof!"); } } Methods usually go after the data When we ask a particular Dog to bark, it says “Woof!” Only Dog objects can bark; the class Dog cannot bark
32
Methods Primitives have operations, classes have methods
You cannot define new primitives, but you can define new classes You cannot define new operations, but you can define new methods Here we will talk about using methods supplied by Java, not defining new ones
33
Methods contain statements
A statement causes the object to do something (A better word would be “command”—but it isn’t) Example: System.out.println("Woof!"); This causes the particular Dog to “print” (actually, display on the screen) the characters Woof!
34
Methods may contain temporary data
Data described in a class exists in all objects of that class Example: Every Dog has its own name and age A method may contain local temporary data that exists only until the method finishes Example: void wakeTheNeighbors( ) { int i = 50; // i is a temporary variable while (i > 0) { bark( ); i = i – 1; } }
35
Sending messages to objects
We don’t perform operations on objects, we “talk” to them This is called sending a message to the object A message looks like this: object.method(extra information) The object is the thing we are talking to The method is a name of the action we want the object to take The extra information is anything required by the method in order to do its job Examples: g.setColor(Color.pink); amountOfRed = Color.pink.getRed( );
36
Messages and methods Messages can be used to:
Tell an object some information Ask an object for information (usually about itself) Tell an object to do something Any and all combinations of the above A method is something inside the object that responds to your messages A message contains commands to do something Java contains thousands of classes, each typically containing dozens of methods When you program you use these classes and methods, and also define your own classes and methods
37
Classes always contain constructors
A constructor is a piece of code that “constructs,” or creates, a new object of that class If you don’t write a constructor, Java defines one for you (behind the scenes) You can write your own constructors Example: class Dog { String name; int age; Dog(String n, int age) { name = n; this.age = age; } } (This part is the constructor)
38
Defining constructors
A constructor is code to create an object You can do other work in a constructor, but you shouldn’t The syntax for a constructor is: ClassName(parameters) { …code… } The ClassName has to be the same as the class that the constructor occurs in The parameters are a comma-separated list of variable declarations
39
Parameters We usually need to give information to constructors and to methods A parameter is a variable used to hold the incoming information A parameter must have a name and a type You supply values for the parameters when you use the constructor or method The parameter name is only meaningful within the constructor or method in which it occurs
40
Diagram of program structure
File Class Variables Constructors Variables Methods A program consists of one or more classes Typically, each class is in a separate .java file
41
Summary A program consists of one or more classes
A class is a description of a kind of object In most cases, it is the objects that do the actual work A class describes data, constructors, and methods An object’s data is information about that object An object’s methods describe how the object behaves A constructor is used to create objects of the class Methods (and constructors) may contain temporary data and statements (commands)
42
Writing and running programs
When you write a program, you are writing classes and all the things that go into classes Your program typically contains commands to create objects (that is, “calls” to constructors) Analogy: A class is like a cookie cutter, objects are like cookies. When you run a program, it creates objects, and those objects interact with one another and do whatever they do to cause something to happen Analogy: Writing a program is like writing the rules to a game; running a program is like actually playing the game You never know how well the rules are going to work until you try them out
43
Getting started Question: Where do objects come from?
Answer: They are created by other objects. Question: Where does the first object come from? Answer: Programs have a special main method, not part of any object, that is executed in order to get things started The main method is defined in a class, but it belongs to the class itself, not to any specific objects of that class The special keyword static says that the method belongs to the class, not to objects of the class public static void main(String[ ] args) { Dog fido = new Dog("Fido", 5); // creates a Dog }
44
A complete program using a class
class Dog { String name; int age; Dog(String n, int age) { name = n; this.age = age; } void bark() { System.out.println("Woof!"); } void wakeTheNeighbors( ) { int i = 50; while (i > 0) { bark( ); i = i – 1; } } public static void main(String[ ] args) { Dog fido = new Dog("Fido", 5); fido.wakeTheNeighbors(); } } // ends the class
45
null If you declare a variable to have a given object type, for example, Person john; String name; ...and if you have not yet assigned a value to it, for example, with john = new Person(); String name = “John Smith"; ...then the value of the variable is null null is a legal value, but there isn’t much you can do with it It’s an error to refer to its fields, because it has none It’s an error to send a message to it, because it has no methods The error you will see is NullPointerException
46
String A String is an object, but...
...because Strings are used so much, Java gives them some special syntax There are String literals: "This is a String" (Almost) no other objects have literals There is an operation, concatenation, on Strings: "Dave" + "Matuszek" gives "DaveMatuszek" In other respects, Strings are just objects
47
String methods A String, is immutable
Once you create it, there are no methods to change it But you can easily make new Strings: myName = "Dave"; myName = "Dr. " + myName; This is kind of a subtle point; it will be important later, but you don’t need to understand it right away If s is the name of the string "Hello", then s.length() tells you the number of characters in String s (returns 5) s.toUpperCase() returns the new String "HELLO" (s itself is not changed) But you can say s = s.toUpperCase();
48
String concatenation + usually means “add,” but if either operand (thing involved in the operation) is a String, then + means concatenation If you concatenate anything with a String, that thing is first turned into a String For example, you can concatenate a String and a number: System.out.println("The price is $" + price); + as the concatenation operator is an exception to the rule: Primitives have operations, Objects have methods
49
String concatenation Be careful, because + also still means addition
int x = 3; int y = 5; System.out.println(x + y + " != " + x + y); The above prints 8 != 35 “Addition” is done left to right--use parentheses to change the order
50
Printing out results, part 1
In Java, “print” really means “display on the screen” Actually printing on paper is much harder! System is one of Java’s built-in classes System.out is a data object in the System class that knows how to “print” to your screen We can “talk to” (send messages to) this mysterious object without knowing very much about it
51
Printing out results, part 2
System.out is a object with useful methods that will let you print anything: print(x) turns x into a String and displays it println(x) (pronounced “print line”) turns x into a String and displays it, then goes to the next line Examples: System.out.print("The sum of x and y is "); System.out.println(x + y);
52
Types of errors There are three general types of errors:
Syntax (or “compile time”) errors Syntax errors are “grammatical” errors and are detected when you compile the program Syntax errors prevent your program from executing Runtime errors Runtime errors occur when you tell the computer to do something illegal Runtime errors may halt execution of your program Logic errors Logic errors are not detected by the computer Logic errors cause your results to be wrong
53
We’re only human For the novice programmers in the room (experienced programmers already know this): Your programs will be full of errors, of all kinds You cannot avoid this, no matter how good you get You cannot learn not to make errors--it’s impossible But, with practice, you will get a little bit better You can and must learn: How to recognize the various types of errors How to find and fix them What is important is not avoiding errors, but knowing how to fix them
54
What to do about errors Error messages are your friends--read them and try to understand them With practice, you can fix most syntax errors almost immediately Runtime and logic errors may take considerably longer to track down and fix Here’s what’s important to remember: Everyone makes lots of stupid errors (and almost all errors are stupid ones--mine included); it’s nothing to be ashamed of However, it is not OK to let those errors survive Approximately 90% of your time will be spent debugging
55
Syntax errors A syntax error is a “grammatical” error--bad punctuation, misuse of keywords, etc. Syntax error messages tell you two things: The line number at which an error was detected Usually, this is the line containing the error In some cases, the actual error is earlier in the program text Use an editor that shows line numbers! What the compiler thinks the problem is Since the compiler cannot know what you meant, the message is only a “best guess,” and is sometimes misleading Syntax errors can cascade: An early error can cause spurious error messages later in the program Always fix the earliest message first If later messages don’t make sense, try recompiling
56
Example syntax errors a = g1 + g2; a = 5; a = b;
System.out.println("(g1 == g2) = " + (g1 == g2); ')' expected System.out.println("(g1 == g2) = " + (g1 == g2))); ’;' expected a = g1 + g2; cannot resolve symbol -- variable a a was never declared; or a was declared, but not where it can be seen from here a = 5; <identifier> expected This is a statement, and statements can only occur inside methods a = b; variable b might not have been initialized
57
Runtime errors A runtime error occurs when your program does something illegal Runtime errors typically stop your program Runtime errors can be “caught” by your program, thus allowing the program to continue running We’ll discuss how to do this later in the course Runtime errors are usually caused by something the program did (or failed to do) earlier in execution Because the cause of the error is somewhere else in the program, runtime errors are usually harder to solve
58
A common runtime error } What kind of error it was
java.lang.NullPointerException at Test.run(Test.java:22) at Test.main(Test.java:6) at __SHELL1.run(__SHELL1.java:6) at bluej.runtime.ExecServer.suspendExecution(ExecServer.java:187) at bluej.runtime.ExecServer.main(ExecServer.java:69) } What kind of error it was Traceback: How your program got to where the error was detected (in line 22 of the file Test.java) The part of the traceback in your code (line 22 of the file, in your run method, called from line 6 of the file, in your main method) The part of the traceback in the Java and BlueJ system; you can pretty much ignore this part
59
Null pointer exceptions
The NullPointerException is one of the most common runtime errors It occurs when you send a message to a null variable (a non-primitive variable that doesn’t refer to an actual object) The null variable causing the problem is always just before a dot Example: g.drawLine(x1, y1, x2, y2); If this caused a NullPointerException, the variable g must have been null You probably never initialized g Java tries to catch uninitialized variables, but it cannot catch them all
60
Assertion errors assert 2 + 2 == 5;
Exception in thread "main" java.lang.AssertionError at Test.run(Test.java:9) at Test.main(Test.java:6) assert = 5: "2 + 2 is actually " + (2 + 2); Exception in thread "main" java.lang.AssertionError: is actually at Test.run(Test.java:9) at Test.main(Test.java:6) Use assert statements to tell what you believe will always be true at a given point in the program assert statements are best used as an “early warning system,” rather than as a debugging tool once errors are known to happen assert statements are also valuable as documentation
61
Logic errors A logic error is when your program compiles and runs just fine, but does the wrong thing In very simple programs, logic errors are usually easy to find and fix, if they occur at all In all but the simplest of programs, 10% of your time is spent writing the program and fixing the syntax errors (more if you are still learning the syntax) 90% of your time is spent finding and fixing runtime and logic errors Logic errors can take hours, or even days, to find Allocate your time accordingly!
62
Make better use of your time
While you cannot avoid making errors, you can prepare for them Keep your programs as simple as possible Indent properly so you can see the structure of your code Comment your programs so you can find things again Write test cases and use them “Write a little, test a little” Write assert statements for the things that you “know” cannot possibly happen Programming is a creative activity, and can be very enjoyable and satisfying For most of us, debugging is not the fun part
63
Approaches to finding errors
Try a random change and see if it helps “An infinite number of monkeys, given an infinite number of typewriters, will eventually produce the complete works of Shakespeare” No monkey has ever passed this course You can’t afford this approach--it’s stupid and doesn’t work Better approach: Think about what could have caused the results you see, and then look for where that might have occurred Advantage: Leads you directly to the error Disadvantage: Not always possible to figure out what could have happened
64
Good approaches, I Put in print statements Use a Debugger
Advantage: Helps you see what the program is doing Disadvantage: You have to take them out again Use a Debugger A debugger is a program that lets you step through your program line by line and see exactly what it is doing Advantages: Takes no prior preparation Lets you see exactly what the program is doing Disadvantages You have to learn to use one (but it’s worth the trouble!) BlueJ’s built-in debugger doesn’t always work well
65
Good approaches, II Explain your code to a friend (even if your friend can’t program) Advantage: Forces you to actually look at what you did Disadvantage: Requires you to have friends In a pinch, even your dog will do (if you can get him to hold still long enough) Note: This is not a violation of academic honesty! In extremis: Throw out the offending code and rewrite it Advantages: Usually works Usually makes your code simpler Disadvantage: Can be psychologically difficult
66
A “best” approach According to the Extreme Programming (XP) philosophy, you should write a suite of tests before you write the code This helps clarify what the code is supposed to do It’s a good idea to know this before starting to program! Having a test suite also makes it much less risky to change and improve working code The mantra is: “Write a little, test a little.” That is, make changes in small steps, and ensure after each step that the code still works This only makes sense if running the tests is fast and simple JUnit, which we will discuss, is a tool for building and running test suites
67
Testing is your responsibility
You are expected to turn in correct programs, or as nearly correct as you can make them Testing is a vital part of writing programs Test your program, not only with “typical” data, but also all the weird and unusual cases that you can think of When I supply example data, it is only to help explain what your program should do; you should never think of such data as an adequate test set We will usually test your program with data you have never seen To get 100%, your programs must pass every test and have good style Programs with syntax errors are worth zero points (You’ve done less than 10% of the work)
68
Why such high standards?
Large programs are the most complex entities ever devised by mankind Large programs consist of thousands of methods and hundreds of thousands of lines A single error can cause catastrophic failure There are a great many examples, from space vehicles crashing to deaths from badly programmed medical equipment We give partial credit for “mostly working” programs--and, believe it or not, I think this is generous
69
Classes form a hierarchy
Classes are arranged is a treelike hierarchy There is one class at the top, or root, of the hierarchy, named Object In computer science we draw trees upside-down, with the root at the top Every class except Object has one “parent” class, or superclass Each class is a subclass of its superclass
70
What is the class hierarchy for?
Classes inherit from their superclasses A class has not only its own fields and methods, but also: Every field described in any class above it Every method described in any class above it Classes do not inherit constructors, however Hence, a class may contain much more information than is obvious from the class description
71
Example of inheritance
class Employee extends Person { double hourlyWage; void pay(double hoursWorked) { System.out.println("Pay to the order of: " name + " $" hoursWorked * hourlyWage); } } An Employee has a name, an age, an hourlyWage, and birthday and pay methods.
72
Classes class MyClass extends ThatClass implements SomeInterface, SomeOtherInterface {...} A top-level class can be public or package (default) A class can be final, meaning it cannot be subclassed A class subclasses exactly one other class (default: Object) A class can implement any number of interfaces abstract class MyClass extends ThatClass implements SomeInterface, SomeOtherInterface {...} Same rules as above, except: An abstract class cannot be final A class must be declared abstract if: It contains abstract methods It implements an interface but does not define all the methods of that interface Any class may be declared to be abstract An abstract class can (and does) have constructors You cannot instantiate an abstract class
73
Why inheritance? Java provides a huge library of pre-written classes
Sometimes these classes are exactly what you need Sometimes these classes are almost what you need It’s easy to subclass a class and override the methods that you want to behave differently Inheritance is a way of providing similar behavior to different kinds of objects, without duplicating code You should extend a class (and inherit from it) only if: Your new class really is a more specific kind of the superclass You want your new class to have most or all of the functionality of the class you are extending You need to add to or modify the capabilities of the superclass You should not extend a class merely to use some of its features Composition is a better solution in this case
74
What are abstract classes for?
Abstract classes are suitable when you can reasonably implement some, but not all, of the behavior of the subclasses Example: You have a board game in which various kinds of animals move around All animals can move(), eat(), drink(), hide(), etc. Since these are identical or similar, it makes sense to have a default move() method, a default drink() method, etc. If you have a default draw() method, what would it draw? Since you probably never want an Animal object, but just specific animals (Dog, Cat, Mouse, etc.), you don’t need to be able to instantiate the Animal class Make Animal abstract, with an abstract void draw() method
75
Interfaces interface MyInterface extends SomeOtherInterface {...}
An interface can be public or package An interface cannot be final A class can implement any number of interfaces An interface can declare (not define) methods All declared methods are implicitly public and abstract An interface can define fields, classes, and interfaces Fields are implicitly static, final, and public Classes are implicitly static and public An interface cannot declare constructors It’s OK (but unnecessary) to explicitly specify implicit attributes
76
What are interfaces for?
Inheritance lets you guarantee that subclass objects have the same methods as their superclass objects Interfaces let you guarantee that unrelated objects have the same methods Problem: On your GUI, you have an area in which you want to be able to draw some object, but you don’t know yet what kind of object it will be Solution: Define a Drawable interface, with a method draw() Make your tables, graphs, line drawings, etc., implement Drawable In your GUI, call the object’s draw() method (legal for any Drawable object) If you didn’t have interfaces, here’s what you would have to do: if (obj instanceof Table) ((Table)obj).draw(); else if (obj instanceof Graph) ((Graph)obj).draw(); else if (obj instanceof LineDrawing) ((LineDrawing)obj).draw(); // etc. Worse, to add a new type of object, you have to change a lot of code
77
Declarations and assignments
Suppose class Cat extends Animal implements Pet {...} and class Persian extends Cat {...} and Cat puff = new Cat(); Then the following are true: puff instanceof Cat, puff instanceof Animal, puff instanceof Pet The following is not true: puff instanceof Persian To form the negative test, say !(puff instanceof Persian) The following declarations and assignments are legal: Animal thatAnimal = puff; Animal thatAnimal = (Animal)puff; // same as above, but explicit upcast Pet myPet = puff; // a variable can be of an interface type Persian myFancyCat = (Persian)puff; // does a runtime check The following is also legal: void feed(Pet p, Food f) {...} // interface type as a parameter
78
Inner Classes I Inner classes are classes declared within another class A member class is defined immediately within another class A member class may be static A member class may be abstract or final (but not both) A member class may be public, protected, package, or private A local class is declared in a constructor, method, or initializer block A local class may be abstract or final (but not both) A local class may access only final variables in its enclosing code An anonymous class is a special kind of local class
79
Inner Classes II An anonymous inner class is a kind of local class
An anonymous inner class has one of the following forms: new NameOfSuperclass(parameters) { class body } new NameOfInterface() { class body } Anonymous inner classes cannot have explicit constructors A static member class is written inside another class, but is not actually an inner class A static member class has no special access to names in its containing class To refer to the static inner class from a class outside the containing class, use the syntax OuterClassName.InnerClassName A static member class may contain static fields and methods
80
What are inner classes for?
Sometimes a class is only needed by one other class Example: A class to handle an event, such as a button click, is probably needed only in the GUI class Having such a class available at the top level, where it isn’t needed, just adds clutter It’s best to “hide” such classes from other classes that don’t care about it Sometimes a class needs access to many variables and methods of another class Again, an event handler is a good example Making it an inner class gives it full access Sometimes a class is only needed once, for one object, in one specific place Most event handlers are like this An anonymous inner class is very handy for this purpose
81
What is a class? A class is primarily a description of objects, or instances, of that class A class contains one or more constructors to create objects A class is a type A type defines a set of possible values, and operations on those values The type of an object is the class that created it But a class can also contain information about itself Anything declared static belongs to the class itself Static variables contain information about the class, not about instances of the class Static methods are executed by the class, not by instances of the class Anything not declared static is not part of the class, and cannot be used directly by the class However, a static method can create (or be given) objects, and can send messages to them
82
Access There are four types of access:
public means accessible from everywhere Making a field public means that it can be changed arbitrarily from anywhere, with no protection Methods should be public only if it’s desirable to be able to call them from outside this class protected means accessible from all classes in this same directory and accessible from all subclasses anywhere Package (default; no keyword) means accessible from all classes in this same directory private means accessible only within this class Note: Making a field private does not hide it from other objects in this same class! In general, it’s best to make all variables as private as possible, and to make methods public enough to be used where they are needed
83
Proper use of fields An object can have fields and methods
When an object is created, It is created with all the non-static fields defined in its class It can execute all the instance methods defined in its class Inside an instance method, this refers to the object executing the method The fields of the object should describe the state of the object All fields should say something significant about the object Variables that don’t describe the object should be local variables, and can be passed from one method to another as parameters The fields of an object should be impervious to corruption from outside This localizes errors in an object to bugs in its class Hence, fields should be a private as possible All public fields should be documented with Javadoc Getters and setters can be used to check the validity of any changes If a class is designed to be subclassed, fields that the subclass needs to access are typically marked protected
84
Composition and inheritance
Composition is when an object of one class uses an object of another class class MyClass { String s; } MyClass has complete control over its methods Inheritance is when a class extends another class class MyClass extends Superclass { ... } MyClass gets all the static variables, instance variables, static methods, and instance methods of Superclass, whether it wants them or not Constructors are not inherited Inheritance should only be used when you can honestly say that a MyClass object is a Superclass object Good: class Secretary extends Employee Bad: class Secretary extends AccountingSystem
85
Constructors A constructor is the only way to make instances of a class Here’s what a constructor does: First, it calls the constructor for its superclass: public MyClass() { super(); ... } // implicit (invisible) call Note that it calls the superclass constructor with no arguments But you can explicitly call a different superclass constructor: public MyClass(int size) { super(size); ... } // explicit call Or you can explicitly call a different constructor in this class: public MyClass() { this(0); ... } // explicit call Next, it adds the instance fields declared in this class (and possibly initializes them) class MyClass { int x; double y = 3.5; ... } // in class, not constructor Next, it executes the code in the constructor: public MyClass() { super(); next = 0; doThis(); doThat(); ... } Finally, it returns the resultant object You can say return; but you can’t explicitly say what to return
86
Constructor chaining Every class always has a constructor
If you don’t write a constructor, Java supplies a default constructor with no arguments If you do write a constructor, Java does not supply a default constructor The first thing any constructor does (except the constructor for Object) is call the constructor for its superclass This creates a chain of constructor calls all the way up to Object The default constructor calls the default constructor for its superclass Therefore, if you write a class with an explicit constructor with arguments, and you write subclasses of that class, Every subclass constructor will, by default, call the superclass constructor with no arguments (which may not still exist) Solutions: Either Provide a no-argument constructor in your superclass, or Explicitly call a particular superclass constructor with super(args)
87
Proper use of constructors
A constructor should always create its objects in a valid state A constructor should not do anything but create objects If a constructor cannot guarantee that the constructed object is valid, it should be private and accessed via a factory method A factory method is a static method that calls a constructor The constructor is usually private The factory method can determine whether or not to call the constructor The factory method can throw an Exception, or do something else suitable, if it is given illegal arguments or otherwise cannot create a valid object public Person create(int age) { // example factory method if (age < 0) throw new IllegalArgumentException("Too young!"); else return new Person(n); }
88
References When you declare a primitive, you also allocate space to hold a primitive of that type int x; double y; boolean b; If declared as a field, it is initially zero (false) If declared as a local variable, it may have a garbage value When you assign this value to another variable, you copy the value When you declare an object, you also allocate space to hold a reference to an object String s; int[ ] counts; Person p; If declared as a field, it is initially null ...but in this case, the value is just a reference to an object You define the variable by assigning an actual object (created by new) to it
89
Methods I A method may: be public, protected, package, or private be static or instance static methods may not refer to the object executing them (this), because they are executed by the class itself, not by an object be final or nonfinal return a value or be void throw exceptions The signature of a method consists of its name and the number and types (in order) of its formal parameters You overload a method by writing another method with the same name but a different signature You override an inherited method by writing another method with the same signature When you override a method: You cannot make it less public (public > protected > package > private) You cannot throw additional exceptions (you can throw fewer) The return types must be compatible
90
Methods II A method declares formal parameters and is “called” with actual parameters void feed(int amount) { hunger -= amount; } // amount is formal myPet.feed(5); // 5 is actual But you don’t “call” a method, you send a message to an object You may not know what kind of object myPet is A dog may eat differently than a parakeet When you send a message, the values of the actual parameters are copied into the formal parameters If the parameters are object types, their “values” are references The method can access the actual object, and possibly modify it When the method returns, formal parameters are not copied back However, changes made to referenced objects will persist
91
Methods III Parameters are passed by assignment, hence:
If a formal parameter is double, you can call it with an int ...unless it is overloaded by a method with an int parameter If a formal parameter is a class type, you can call it with an object of a subclass type Within an instance method, the keyword this acts as an extra parameter (set to the object executing the method) Local variables are not necessarily initialized to zero (or false or null) The compiler tries to keep you from using an uninitialized variable Local variables, including parameters, are discarded when the method returns Any method, regardless of its return type, may be used as a statement
92
Proper use of methods I Methods that are designed for use by other kinds of objects should be public All public methods should be documented with Javadoc public methods that can fail, or harm the object if called incorrectly, should throw an appropriate Exception Methods that are for internal use only should be private private methods can use assert statements rather than throw Exceptions Methods that are only for internal use by this class, or by its subclasses, should be protected This isn’t great, in my opinion, but it’s the best Java has Methods that don’t use any instance variables or instance methods should be static Why require an object if you don’t need it?
93
Proper use of methods II
Ideally, a method should do only one thing You should describe what it does in one simple sentence The method name should clearly convey the basic intent It should usually be a verb The sentence should mention every source of input (parameters, fields, etc.) and every result There is no such thing as a method that’s “too small” Methods should usually do no input/output Unless, of course, that’s the main purpose of the method Exception: Temporary print statements used for debugging Methods should do “sanity checks” on their inputs Publicly available methods should throw Exceptions for bad inputs
94
Proper use of polymorphism
Methods with the same name should do the same thing Method overloading should be used only when the overloaded methods are doing the same thing (with different parameters) Classes that implement an interface should implement corresponding methods to do the same thing Method overriding should be done to change the details of what the method does, without changing the basic idea Methods shouldn’t duplicate code in other methods An overloaded method can call its namesake with other parameters A method in a subclass can call an overridden method m(args) in the superclass with the syntax super.m(args) Typically, this call would be made by the overriding method to do the usual work of the method, then the overriding method would do the rest
95
Program design Good program design pays for itself many times over when it comes to actually writing the code Good program design is an art, not a science Generally, you want: The simplest design that could possibly work Classes that stand by themselves, and make sense in isolation Aptly named methods that do one thing only, and do it well Classes and methods that can be tested (with JUnit) “Make everything as simple as possible, but not simpler.” -- Albert Einstein
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.