1 / 44

Introduction to OOP in Java

Introduction to OOP in Java. “When a programming language is created that allows programmers to program in simple English, it will be discovered that programmers cannot speak English.” - Anonymous. High Level Languages.

jdebose
Download Presentation

Introduction to OOP in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to OOP in Java “When a programming language is created that allows programmers to program in simple English, it will be discovered that programmers cannot speak English.”- Anonymous

  2. High Level Languages • Assembly language, still not so easy, and lots of commands to accomplish things • High Level Computer Languages provide the ability to accomplish a lot with fewer commands than machine or assembly language in a way that is hopefully easier to understand int sum;int count = 0;int done = -1;while( list[count]!= -1 ) sum += list[count];

  3. Java • There are hundreds of high level computer languages. Java, C++, C, Basic, Fortran, Cobol, Lisp, Perl, Prolog, Eiffel, Python • The capabilities of the languages vary widely, but they all need a way to do • declarative statements • conditional statements • iterative or repetitive statements • A compiler is a program that converts commands in high level languages to machine language instructions

  4. Characteristics of Java • Java is simple • Java is object-oriented • Java is distributed • Java is interpreted • Java is robust • Java is secure • Java is architecture-neutral • Java is portable • Java is multithreaded • Java is dynamic 4

  5. Some Salient Characteristics of Java • Java is platform independent: the same program can run on any correctly implemented Java system • Java is object-oriented: • Structured in terms of classes, which group data with operations on that data • Can construct new classes by extending existing ones • Java designed as • A core language plus • A rich collection of commonly available packages • Java can be embedded in Web pages Appendix A: Introduction to Java 5

  6. The output of the compiler is .class file The Interpreter's are sometimes referred to as the Java Virtual Machines

  7. Compiling and Executing a Java Program Appendix A: Introduction to Java 7

  8. Java • A Java program is mostly a collection of objects talking to other objects by invoking each other's methods • Every object is of a certain type, and that type is defined by a class or an interface • Class A template that describes the kinds of state and behavior that objects of its type support. • ■ Object At runtime, when the Java Virtual Machine (JVM) encounters the new keyword, it will use the appropriate class to make an object that is an instance of that class. That object will have its own state and access to all of the behaviors defined by its class. • ■ State (instance variables) Each object (instance of a class) will have its own unique set of instance variables as defined in the class. Collectively, the values assigned to an object's instance variables make up the object's state. • ■ Behavior (methods) When a programmer creates a class, he creates methods for that class. Methods are where the class's logic is stored and where the real work gets done. They are where algorithms get executed and data gets manipulated

  9. Identifiers and Keywords • All the Java components we just talked about—classes, variables, and methods— need names. In Java, these names are called identifiers, and, as you might expect, there are rules for what constitutes a legal Java identifier • Like all programming languages, Java has a set of built-in keywords. These keywords must not be used as identifiers • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore (_). Identifiers cannot start with a digit!

  10. Continue… • Examples of legal and illegal identifiers follow. First some legal identifiers: • int _a; • int $c; • int ______2_w; • int _$; • int this_is_a_very_detailed_name_for_an_identifier; • The following are illegal: • int :b; • int -d; • int e#; • int .f; • int 7g;

  11. Declarations and Access Control • Classes and interfaces The first letter should be capitalized, and if several words are linked together to form the name, the first letter of the inner words should be uppercase (a format that's sometimes called "CamelCase"). For classes, the names should typically be nouns. Here are some examples: • Dog • Account • PrintWriter • For interfaces, the names should typically be adjectives, like these: • Runnable • Serializable • Methods The first letter should be lowercase, and then normal CamelCase rules should be used. In addition, the names should typically be verb-noun pairs. For example: • getBalance • doCalculation • setCustomerName • ■ Variables Like methods, the CamelCase format should be used, but starting with a lowercase letter. Oracle recommends short, meaningful names, which sounds good to us. Some examples: • buttonWidth • accountBalance • myString • ■ Constants Java constants are created by marking variables static and final. They should be named using uppercase letters with underscore characters as separators: • MIN_HEIGHT

  12. Define Classes • When you write code in Java, you're writing classes or interfaces • Within those classes, as you know, are variables and methods (plus a few other things) • How you declare your classes, methods, and variables dramatically affects your code's behavior. • For example, a public method can be accessed from code running anywhere in your application

  13. Source File Declaration Rules • ■ There can be only one public class per source code file. • ■ If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Dog { } must be in a source code file named Dog.java. • ■ If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present. • ■ If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn't a package statement, then the import statement(s) must be the first line(s) in the source code file

  14. Continue.. • If there are no package or import statements, the class declaration must be the first line in the source code file. • ■ import and package statements apply to all classes within a source code file. • In other words, there's no way to declare multiple classes in a file and have them in different packages or use different imports. • ■ A file can have more than one nonpublic class. • ■ Files with no public classes can have a name that does not match any of the classes in the file.

  15. A Simple Java Program Example 1.1 package chapter1; public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); String s = “Hello World\n”; System.out.println(s); //output simple string } }

  16. source code (Hello.java) compile byte code (Hello.class) execute output The command line To run a Java program using your Command Prompt: • change to the directory of your program cd • compile the program javac Hello.java The javac command is used to invoke Java's compiler • execute the program java Hello The java command is used to invoke the Java Virtual Machine (JVM).

  17. Using public static void main(String[ ] args) • main() is the method that the JVM uses to start execution of a Java program • As far as the compiler and the JVM are concerned, the only version of main() with superpowers is the main() with this signature: • public static void main(String[] args) • Other versions of main() with other signatures are perfectly legal, but they're treated as normal methods.

  18. Import Statements and the Java API • There are a gazillion Java classes in the world. The Java API has thousands of classes and the Java community has written the rest. • All Java programmers everywhere use a combination of classes they wrote and classes that other programmers wrote. Suppose we created the following: • public class ArrayList { • public static void main(String[] args) { • System.out.println("fake ArrayList class"); • } • } • This is a perfectly legal class, but as it turns out, one of the most commonly used classes in the Java API is also named ArrayList, or so it seems…. The API version's actual name is java.util.ArrayList. That's its fully qualified name. The use of fully qualified names is what helps Java developers make sure that two versions of a class like ArrayList don't get confused.

  19. So now let's say that I want to use the ArrayList class from the API: public class MyClass { public static void main(String[] args) { java.util.ArrayList<String> a = new java.util.ArrayList<String>(); } } If we had a large program, we might end up using ArrayLists many times. import statements to the rescue! Instead of the preceding code, our class couldlook like this: import java.util.ArrayList; public class MyClass { public static void main(String[] args) { ArrayList<String> a = new ArrayList<String>(); } } We can interpret the import statement as saying, "In the Java API there is a package called 'util', and in that package is a class called 'ArrayList'. Whenever you see the word 'ArrayList' in this class, it's just shorthand for: 'java.util.ArrayList'.“ If you're a C programmer, you might think that the import statement is similar to an #include. Not really. All a Java import statement does is save you some typing. That's it. As we just implied, a package typically has many classes. The import statement offers yet another keystroke-saving capability. Let's say you wanted to use a few different classes from the java.util package: ArrayList and TreeSet. You can add a wildcard character (*) to your import statement that means

  20. Static, Import Statements • Static class members can exist in the classes you write and in a lot of the classes in the Java API • The static keyword denotes that a member variable, or method, can be accessed without requiring an instantiation of the class to which it belongs. In simple terms, it means that you can call a method, even if you've never created the object to which it belongs! • ultimately the only value import statements have is that they save typing and they can make your code easier to read. • Static imports can be used when you want to "save typing" while using a class's static members. • Here's a "before and after" example using a few static class members provided by a commonly used class in the Java API, java.lang.Integer. • Before static imports: • public class TestStatic { • public static void main(String[] args) { • System.out.println(Integer.MAX_VALUE); • System.out.println(Integer.toHexString(42)); • } • }

  21. After static imports • import static java.lang.Integer.*; • import static java.lang.System.out; • public class TestStaticImport { • public static void main(String[] args) { • out.println(MAX_VALUE); • out.println(toHexString(42)); • } • } • Both classes produce the same output: • 2147483647 • 2a

  22. Here are a couple of rules for using static imports: • ■ You must say import static; you can't say static import. • ■ Watch out for ambiguously named static members. For instance, if you do a static import for both the Integer class and the Long class, referring to MAX_VALUE will cause a compiler error, since both Integer and Long have a MAX_VALUE constant, and Java won't know which MAX_VALUE you're referring to.

  23. Another Java program public class Hello2 { public static void main(String[] args) { System.out.println("Hello, world!"); System.out.println(); System.out.println("This program produces"); System.out.println("four lines of output"); } } • The code in this program instructs the computer to print four messages on the screen.

  24. Structure of Java programs public class <name> { public static void main(String[] args) { <statement(s)>; } } • Every executable Java program consists of a class... • that contains a method named main... • that contains the statements to be executed

  25. Class Declarations and Modifiers • The following code is a bare-bones class declaration: • class MyClass { } • This code compiles just fine, but you can also add modifiers before the class declaration. In general, modifiers fall into two categories: • ■ Access modifiers (public, protected, private) • ■ Nonaccess modifiers (including strictfp, final, and abstract) • Access control in Java is a little tricky, because there are four access controls (levels of access) but only three access modifiers. The fourth access control level (called default or package access) is what you get when you don't use any of the three access modifiers • In other words, every class, method, and instance variable you declare has an access control, whether you explicitly type one or not.

  26. Class Access • What does it mean to access a class? When we say code from one class (class A) has access to another class (class B), it means class A can do one of three things: • ■ Create an instance of class B. • ■ Extend class B (in other words, become a subclass of class B). • ■ Access certain methods and variables within class B, depending on the access control of those methods and variables • In effect, access means visibility. If class A can't see class B, the access level of the methods and variables within class B won't matter; class A won't have any way to access those methods and variables.

  27. Default Access • A class with default access has no modifier preceding it in the declaration! It's the access control you get when you don't type a modifier in the class declaration. • Think of default access as package-level access, because a class with default access can be seen only by classes within the same package. • For example, if class A and class B are in different packages, and class A has default access, class B won't be able to create an instance of class A or even declare a variable or return type of class A. In fact, class B has to pretend that class A doesn't even exist, or the compiler will complain. • Look at the following source file: • package cert; • class Beverage { } • Now look at the second source file: • package exam.stuff; • import cert.Beverage; • class Tea extends Beverage { }

  28. Continue… • As you can see, the superclass (Beverage) is in a different package from the subclass (Tea). The import statement at the top of the Tea file is trying (fingers crossed) to import the Beverage class. The Beverage file compiles fine, but when we try to compile the Tea file, we get something like this: • Can't access class cert.Beverage. Class or interface must be public, in same package, or an accessible member class. import cert.Beverage;

  29. Public Access • A class declaration with the public keyword gives all classes from all packages access to the public class. • In other words, all classes in the Java Universe (JU) have access to a public class. • Don't forget, though, that if a public class you're trying to use is in a different package from the class you're writing, you'll still need to import the public class.

  30. Other (Nonaccess) Class Modifiers • You can modify a class declaration using the keyword final, abstract, or strictfp • These modifiers are in addition to whatever access control is on the class, so you could, for example, declare a class as both public and final • You're free to use strictfp in combination with final, for example, but you must never, ever, ever mark a class as both final and abstract. • Strictfp ensures that you get exactly the same results from your floating point calculations on every platform. If you don't use strictfp, the JVM implementation is free to use extra precision where available. • Marking a class as strictfp means that any method code in the class will conform to the IEEE 754 standard rules for floating points. Without that modifier, floating points used in the methods might behave in a platform-dependent way. If you don't declare a class as strictfp, you can still get strictfp behavior on a method-by-method basis, by declaring a method as strictfp.

  31. Final Classes • When used in a class declaration, the final keyword means the class can't be subclassed. • In other words, no other class can ever extend (inherit from) a final class, and any attempts to do so will result in a compiler error. • You should make a final class only if you need an absolute guarantee that none of the methods in that class will ever be overridden. • If you're deeply dependent on the implementations of certain methods, then using final gives you the security that nobody can change the implementation. • You'll notice many classes in the Java core libraries are final. For example, the String class cannot be subclassed

  32. Example • Let's modify our Beverage example by placing the keyword final in the • declaration: • package cert; • public final class Beverage { • public void importantMethod() { } • } • Now let's try to compile the Tea subclass: • package exam.stuff; • import cert.Beverage; • class Tea extends Beverage { } • We get an error—something like this: Can't subclass final classes: class cert.Beverage class Tea extends Beverage{ 1 error

  33. Abstract Classes • An abstract class can never be instantiated • Its sole purpose, mission in life, is to be extended (subclassed). • Why make a class if you can't make objects out of it? Because the class might be just too, well, abstract. • For example, imagine you have a class Car that has generic methods common to all vehicles. But you don't want anyone actually creating a generic, abstract Car object. How would they initialize its state? What color would it be? How many seats? Horsepower? All-wheel drive? Or more importantly, how would it behave? In other words, how would the methods be implemented?

  34. Continue.. • Take a look at the following abstract class: • abstract class Car { • private double price; • private String model; • private String year; • public abstract void goFast(); • public abstract void goUpHill(); • public abstract void impressNeighbors(); • // Additional, important, and serious code goes here • } • Notice that the methods marked abstract end in a semicolon rather than curly braces.

  35. Exercise • Create an abstract superclass named Fruit and a concrete subclass named Apple. The superclass should belong to a package called food and the subclass can belong to the default package (meaning it isn't put into a package explicitly). Make the superclass public and give the subclass default access. • 1. Create the superclass as follows: • package food; • public abstract class Fruit{ • private String name; • private String color; • public abstract calcPrice(); • /* any code you want */} • 2. Create the subclass in a separate file as follows: • import food.Fruit; • class Apple extends Fruit{ /* any code you want */}

  36. Grouping Classes: The Java API • API = Application Programming Interface • Java = small core + extensive collection of packages • A package consists of some related Java classes: • Swing: a GUI (graphical user interface) package • AWT: Application Window Toolkit (more GUI) • util: utility data structures • The import statement tells the compiler to make available classes and methods of another package • A main method indicates where to begin executing a class (if it is designed to be run as a program) Appendix A: Introduction to Java 37

  37. Syntax and syntax errors • syntax: The set of legal structures and commands that can be used in a particular programming language. • syntax error or compiler error: A problem in the structure of a program that causes the compiler to fail. • If you type your Java program incorrectly, you may violate Java's syntax and see a syntax error. public class Hello { pooblic static void main(String[] args) { System.owt.println("Hello, world!")_ } }

  38. Methods • A Java method defines a group of statements as performing a particular operation • static indicates a static method or class method • A method that is not static is an instance method • All method arguments are call-by-value • Primitive type: value is passed to the method • Method may modify local copy but will not affect caller’s value • Object reference: address of objectis passed 39

  39. Static method syntax • The structure of a static method:public class <Class Name> { public static void <Method name> () {<statements>; }} • Example:public static void printCheer() { System.out.println(“Three cheers for Pirates!"); System.out.println(“Huzzah!"); System.out.println(“Huzzah!"); System.out.println(“Huzzah!");}

  40. Static methods example public class TwoMessages { public static void main(String[] args) { printCheer(); System.out.println(); printCheer(); } public static void printCheer() { System.out.println(“Three cheers for Pirates!"); System.out.println(“Welcome!"); System.out.println(“Welcome!"); System.out.println(“Welcome!"); } } Program's output: Three cheers for Pirates! Welcome! Welcome! Welcome! Three cheers for Pirates! Welcome! Welcome! Welcome!

  41. Methods calling each other • One static method may call another: public class TwelveDays { public static void main(String[] args) { day1(); day2(); } public static void day1() { System.out.println("A partridge in a pear tree."); } public static void day2() { System.out.println("Two turtle doves, and"); day1(); } } Program's output: A partridge in a pear tree. Two turtle doves, and A partridge in a pear tree.

  42. public static void day2() { System.out.println("Two turtle doves, and"); day1(); } Control flow of methods • When a method is called, a Java program 'jumps' into that method, executes all of its statements, and then 'jumps' back to where it started. public class TwelveDays { public static void main(String[] args) { day1(); day2(); } } public static void day1() { System.out.println("A partridge in a pear tree."); }

  43. When to use static methods • You should place a group of statements into a static method if any of the following conditions is met: • The statements are related to each other and form a combined part of the program's structure. • The statements are repeated in the program. • You need not create static methods for the following: • Individual statements.(One single println in its own static method does not improve the program, and may make it harder to read.) • Unrelated or weakly related statements.(If the statements are not closely related, consider splitting the method into two or more smaller methods.) • Only blank lines.(It's fine to have blank System.out.println(); statements in the main method.)

More Related