Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed.

Slides:



Advertisements
Similar presentations
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Advertisements

1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
 2005 Pearson Education, Inc. All rights reserved Introduction.
Lab#1 (14/3/1431h) Introduction To java programming cs425
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Intro to Java Part II. Calling an Objects Methods Use qualified names to call the objects methods. To form – you append the method name to an object reference.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
EEC-681/781 Distributed Computing Systems Java Tutorial Wenbing Zhao Cleveland State University
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Introduction to Java CS 331. Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build –stand-alone Java programs –Java.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Copyright © 2003 ProsoftTraining. All rights reserved. Sun Certified Java Programmer Exam Preparation Guide.
Java Software Solutions Lewis and Loftus Chapter 2 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Software Concepts -- Introduction.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
The Java Programming Language
CSC204 – Programming I Lecture 4 August 28, 2002.
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Structure import java_packages; class JavaClass { member variables declarations; void otherMethod( ) { } public static void main(String[]
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
JAVA BASICS Prepared by The Smartpath Information Systems
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Introduction to Java Java Translation Program Structure
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
SESSION 1 Introduction in Java. Objectives Introduce classes and objects Starting with Java Introduce JDK Writing a simple Java program Using comments.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Sung-Dong Kim, Dept. of Computer Engineering, Hansung University Java - Introduction.
JAVA MULTIPLE CHOICE QUESTION.
Java Primer 1: Types, Classes and Operators
Data types and variables
Chapter 9 Inheritance and Polymorphism
Starting JavaProgramming
Java Programming Language
Units with – James tedder
Focus of the Course Object-Oriented Software Development
Chap 2. Identifiers, Keywords, and Types
Presentation transcript:

Introduction to Java

Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Java 2 platform Java virtual machine: execute byte code, just in time (jit) compilation Java 2 enterprise edition (J2EE): service and enterprise applications Java 2 standard edition (J2SE): desktop and personal applications Java 2 Micro edition (J2ME): embedded and consumer devices

J2SE Java virtual machine: java Tools: compiler javac, debugger jdb, Java class disassembler javap, documentation generator javadoc, Core APIs: java.lang, java.util, java.io, java.net, java.security, etc. GUI APIs: java.awt, javax.swing, javax.sound Integration APIs: javax.rmi, java.sql (JDBC), javax.naming (JNDI), org.omg.CORBA

J2EE Superset of J2SE Java servlet (javax.servlet) and Java Server Pages (JSP) (javax.servlet.jsp) Enterprise Java Beans (EJB) javax.ejb and messaging services javax.mail Transaction management javax.transaction

J2ME Connected device configuration (CDC) for devices with large amount of memory and high network bandwidth Connected, limited device configuration (CLDC) for devices with limited memory, low bandwidth, intermittent network connections KVM runs on PDAs and cell phones

Java runtime architecture byte code interpreter CPU byte code compiler CPU native machine code Java CPU Java byte code Java compiler Java source code JVM Java machine Platform independent Platform dependent JVM

Java byte code Byte code format pc program counter optop top of stack vars local variables frame execution environment Garbage-collected heap RISC like instruction set, 32-bit register Stack-based architecture opcode (1-byte) operand1 operand2 …

JVM instruction functions Stack manipulation Array management Arithmetic/logical operations Method invocation/return Exception handling Thread synchronization

JVM security Strong typing: no pointers, array bound checks, dynamic downcast checks Byte code verification: loaded class files satisfy byte code specification Run time access control: discretionary access control based on stack inspection, flexible security policy

Java language Object-Oriented Programming Concepts Language basics Object basics and simple data objects Classes and inheritance Interfaces and packages Common problems/solutions

OO programming concepts What Is an Object? An object is a software bundle of related variables and methods. Software objects are often used to model real-world objects you find in everyday life. What Is a Message? Software objects interact and communicate with each other using messages. What Is a Class? A class is a blueprint or prototype that defines the variables and the methods common to all objects of a certain kind. What Is Inheritance? A class inherits state and behavior from its superclass. Inheritance provides a powerful and natural mechanism for organizing and structuring software programs. What Is an Interface? An interface is a contract in the form of a collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface.

Java language Object-Oriented Programming Concepts Language basics Object basics and simple data objects Classes and inheritance Interfaces and packages Common problems/solutions

Language basics public class BasicsDemo { public static void main(String[] args) { int sum = 0; for (int current = 1; current <= 10; current++){ sum += current; } System.out.println("Sum = " + sum); }

Language basics Variables Operators Expressions, statements, and blocks Control flow statements

Variables Definition: A variable is an item of data named by an identifier Data Types Variable Names Scope Variable Initialization Final Variables

Data types Primitive Data Types: –Integers: byte, short, int, long (8 – 64 bits) –Real numbers: float, double (32, 64 bits) –Others: char (16 bit unicode), boolean Arrays, classes, and interfaces are reference types The value of a reference type variable, in contrast to that of a primitive type, is a reference to (an address of) the value or set of values represented by the variable

Variable names It must be a legal identifier It must not be a keyword, a boolean literal ( true or false ), or the reserved word null It must be unique within its scope By Convention: Variable names begin with a lowercase letter and class names begin with an uppercase letter If a variable name consists of more than one word, the words are joined together, and each word after the first begins with an uppercase letter (for example, isVisible )

Scope A variable's scope is the region of a program within which the variable can be referred to by its simple name Scope determines when the system creates and destroys memory for the variable if (...) { int i = 17;.. } System.out.println("The value of i = " + i); //error

Variable initialization Local variables and member variables can be initialized with an assignment statement when they're declared Parameters and exception-handler parameters cannot be initialized in this way. The value for a parameter is set by the caller

Final variable The value of a final variable cannot change after it has been initialized. Such variables are similar to constants in other languages final int aFinalVar = 0; // or final int blankfinal;... blankfinal = 0;

Language basics Variables Operators Expressions, statements, and blocks Control flow statements

Operators Arithmetic Operators: +, -, *, /, %, ++, -- Relational (>, =, <=, ==, !=) and Conditional Operators (&&, ||, &, |, !, ^) Shift ( >, >>>) and Bitwise Operators (&, |, ~, ^) Assignment Operators (=, op =) Other Operators: op1 ? op2 : op3, new, op1 instanceof op2, [],., (params), (type)

Expressions, statements, blocks An expression is a series of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value A statement forms a complete unit of execution A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed

Control flow statements Statement TypeKeyword looping while, do-while, for decision making if-else, switch-case exception handling try-catch-finally, throw Branching break, continue, label:, return control flow statement details { statement(s) }

Java language Object-Oriented Programming Concepts Language basics Object basics and simple data objects Classes and inheritance Interfaces and packages Common problems/solutions

Object basics The Java platform groups its classes into functional packages Instead of writing your own classes to represent character, string, or numeric data, you should use the classes that are already provided by the Java platform Most of the classes discussed here are members of the java.lang package

Creating objects Point originOne = new Point(23, 94); Rectangle rectOne = new Rectangle(originOne, 100, 200); Rectangle rectTwo = new Rectangle(50, 100); 1.declaration 2.instantiation 3.initialization

Using objects Directly manipulate or inspect its variables Call its methods objectReference.variableName int height = new Rectangle().height objectReference.methodName(argumentList); or objectReference.methodName(); int areaOfRectangle = new Rectangle(100, 50).area();

Cleaning up unused objects The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null

Simple data objects Characters and strings Numbers Arrays

Characters and strings When working with character data, you will typically use either the char primitive type, or one of the following three classes: –String — A class for working with immutable (unchanging) data composed of multiple characters. –StringBuffer — A class for storing and manipulating mutable data composed of multiple characters. This class is safe for use in a multi-threaded environment. –StringBuilder — A faster, drop-in replacement for StringBuffer, designed for use by a single thread only.

Characters char ch = 'a'; char[] firstFiveLetters={ 'a', 'b', 'c', 'd', 'e' }; char ch = string.charAt(i); //Test whether a character is upper case. if (Character.isUpperCase(string.charAt(i)) {... } //Convert a character to lower case. char ch = Character.toLowerCase(string.charAt(i)); //Determine if the character is a letter. if (Character.isLetter(string.charAt(i))) {... }

Strings If your text is not going to change, use a string — a String object is immutable. If your text will change, and will only be accessed from a single thread, use a string builder. If your text will change, and will be accessed from multiple threads, use a string buffer public class StringsDemo { public static void main(String[] args) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); StringBuilder dest = new StringBuilder(len); for (int i = (len - 1); i >= 0; i--) { dest.append(palindrome.charAt(i)); } System.out.format("%s%n", dest.toString()); } }

Strings and compiler The compiler uses the StringBuilder class behind the scenes to handle literal strings and concatenation int len = "Goodbye Cruel World".length(); String s = "Hola Mundo"; The preceding construct is equivalent to, but more efficient than, this one, which ends up creating two identical strings: String s = new String("Hola Mundo"); //don't do this String cat = "cat"; System.out.println("con" + cat + "enation"); The preceding example compiles to something equivalent to: System.out.println( new StringBuffer(). append("con").append(cat).append("enation").toString()); int one = 1; System.out.println("You're number " + one);

Number classes Two reasons that you might use a Number class, instead of the primitive form: –When an object is required — such as when using generic types. For example, to constrain your list to a particular type argument, such as String. You must specify the Integer type, as in ArrayList –When you need the variables or static methods defined by the class, such as MIN_VALUE and MAX_VALUE, that provide general information about the data type

Simple data objects Characters and strings Numbers Arrays

An array is a structure that holds multiple values of the same type. The length of an array is established when the array is created. After creation, an array is a fixed-length structure.

Creating and using arrays public class ArrayDemo { public static void main(String[] args) { int[] anArray; // declare an array of integers anArray = new int[10]; // create an array of integers // assign a value to each array element and print for (int i = 0; i < anArray.length; i++) { anArray[i] = i; System.out.print(anArray[i] + " "); } } } You can write an array declaration like this: float anArrayOfFloats[]; //this form is discouraged new elementType[arraySize]; // create new array boolean[] answers = { true, false, true, true, false }; // initialize array arrayname.length // get size of the array

Java language Object-Oriented Programming Concepts Language basics Object basics and simple data objects Classes and inheritance Interfaces and packages Common problems/solutions

Classes and inheritance Writing classes Manage inheritance Nested classes Enumerated types Annotations Generics

Writing classes

Declaring classes (Optional) An annotation (also called meta-data) public (Optional) Class is publicly accessible abstract (Optional) Class cannot be instantiated final (Optional) Class cannot be subclassed class NameOfClass Name of the class (Optional) comma-separated list of type variables extends Super (Optional) Superclass of the class implements Interfaces (Optional) Interfaces implemented by the class { ClassBody } Provides the class's functionality

Declaring member variables private List items; ElementFunction accessLevel (optional) Access level for the variable –public, protected, private, and default static (optional) Declares a class variable final (optional) variable value cannot change transient (optional) the variable is transient –member variables that should not be serialized volatile (optional) the variable is volatile –Prevents the compiler from performing certain optimizations on a member type name The type and name of the variable

Declaring methods Element (Optional) An annotation (sometimes called meta- data) accessLevel (Optional) Access level for the method static (Optional) Declares a class method (Optional) Comma-separated list of type variables abstract (Optional) Indicates that the method must be implemented in concrete subclasses final (Optional) Indicates that the method cannot be overridden native (Optional) Indicates that the method is implemented in another language synchronized (Optional) Guarantees exclusive access to this method returnType methodName The method's return type and name ( paramList ) The list of arguments to the method throws exceptions (Optional) The exceptions thrown by the method

Providing constructors public Stack() { items = new ArrayList (); } public Stack(int size) { items = new ArrayList (size); } public, private, protected, default

Classes and inheritance Writing classes Manage inheritance Nested classes Enumerated types Annotations Generics

Manage inheritance All Classes are Descendants of Object

Inheritance Every class has one and only one direct superclass (single inheritance) A subclass inherits all the member variables and methods from its superclass a subclass cannot access a private member inherited from its superclass constructors are not members and so are not inherited by subclasses

Overriding and hiding methods An instance method in a subclass with the same signature and return type as an instance method in the superclass overrides the superclass's method a method's signature is its name and the number and the type of its arguments can also override a method with the same signature that returns a subclass of the object returned by the original method. This facility is called covariant return type A subclass cannot override methods that are declared final in the superclass A subclass must override methods that are declared abstract in the superclass, or the subclass itself must be abstract

Overriding and hiding methods You might want to use annotation which instructs the compiler that you intend to override a method in the superclass If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass An instance method cannot override a static method, and A static method cannot hide an instance method

Hiding member variables A member variable that has the same name as a member variable in the superclass hides the superclass's member variable, even if their types are different Within the subclass, the member variable in the superclass cannot be referenced by its simple name, the member variable must be accessed through super we don't recommend hiding member variables

Using super If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of super public class Superclass { public boolean aVariable; public void aMethod() { aVariable = true; } } public class Subclass extends Superclass { public boolean aVariable; //hides aVariable in Superclass //not recommended public void aMethod() { //overrides aMethod in Superclass aVariable = false; super.aMethod(); System.out.format("%b%n", aVariable); System.out.format("%b%n", super.aVariable); } }

Using super The following example illustrates how to use the super keyword to invoke a superclass's constructor Suppose you are writing a transaction-based system and need to throw a checked exception if the transaction fails. Such an exception should include an informative message and a reference to the cause of the problem, another exception, checked or unchecked (Throwable) public final class TransactionFailedException extends Exception { static final long serialVersionUID = L public TransactionFailedException(Throwable cause) { super("Transaction failed", cause) }

What does Object class provide Object class defines the basic state and behavior that all objects might use, such as –the ability to compare oneself to another object, –to convert to a string, –to wait on a condition variable, –to notify other objects that a condition variable has changed, and –to return the class of the object

Methods of Object class The methods of Object class that may need to be overridden by a well-behaved subclass –equals and hashCode –toString In addition, the Object class provides the following handy methods: –getClass (equivalent to Class.forname(“class name”), or className.class) –notify, notifyAll, and wait there is finalize, a special method, called by the garbage collector. It shouldn't be called from regular programs

Final classes and methods make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method to behave in surprising or undesirable ways declare an entire class final prevents the class from being sub-classed. This may be useful when creating an immutable class like the String class

Abstract class and methods model an abstract concept without being able to create an instance of it abstract class Number {... } abstract methods have no implementation abstract class GraphicObject { int x, y.. void moveTo(int newX, int newY) {... } abstract void draw() } class Circle extends GraphicObject { void draw() {... } }

Classes and inheritance Writing classes Manage inheritance Nested classes Enumerated types Annotations Generics

Nested classes class EnclosingClass { … class ANestedClass { … } } define a class within another class when the nested class makes sense only in the context of its enclosing class or when it relies on the enclosing class for its function a nested class has a special privilege: It has unlimited access to its enclosing class's members, even if they are declared private a nested class can be declared static (or not). A static nested class is called just that: a static nested class. A non-static nested class is called an inner class

Nested classes an inner class is associated with an instance of its enclosing class and has direct access to that object's instance variables and methods because an inner class is associated with an instance, it cannot define any static members itself nested class reflects the syntactic relationship between two classes inner class reflects the relationship between objects that are instances of the two classes two special kinds of inner classes: local classes and anonymous classes

interface Iterator { public boolean hasNext(); public next(); public void remove(); } public class Stack { private ArrayList items; //code for Stack's methods and constructors not shown public Iterator iterator() { return new StackIterator(); } private class StackIterator implements Iterator { int currentItem = items.size() - 1; public boolean hasNext() {... } public ArrayList next() {... } public void remove() {... } }

Anonymous class public class Stack { private ArrayList items; // code for Stack's methods and constructors // not shown public Iterator iterator() { return new Iterator () { int currentItem = items.size() - 1; public boolean hasNext() {... } public ArrayList next() {... } public void remove() {... } }; }

Local class public class Stack { private ArrayList items; //code for Stack's methods and constructors not shown public Iterator iterator() { private class StackIterator implements Iterator { int currentItem = items.size() - 1; public boolean hasNext() {... } public ArrayList next() {... } public void remove() {... } } return new StackIterator(); }

Summary of nested class A class defined within another class is called a nested class Like other members of a class, a nested class can be declared static or not A non-static nested class is called an inner class An instance of an inner class can exist only within an instance of its enclosing class and has access to its enclosing class's members even if they are declared private

Types of Nested Classes TypeScopeInner static nested classmemberno inner [non-static] classmemberyes local classlocalyes anonymous classwhere it is definedyes

Classes and inheritance Writing classes Manage inheritance Nested classes Enumerated types Annotations Generics

Enumerated types enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }; The enum declaration defines a class (called an enum type) the constructor for an enum type is implicitly private If you attempt to create a public constructor for an enum type, the compiler displays an error message

public enum Planet { MERCURY(3.303e+23, e6), VENUS(4.869e+24, e6), EARTH …; private final double mass; //in kilograms private final double radius; //in meters Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } public double mass() { return mass; } public double radius() { return radius; } //universal gravitational constant (m3 kg-1 s-2) public static final double G = E-11; public double surfaceGravity() { return G * mass / (radius * radius); } public double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); } }

public static void main(String[] args) { double earthWeight = Double.parseDouble(args[0]); double mass = earthWeight/EARTH.surfaceGravity(); for (Planet p : Planet.values()) { System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass)); } Here's the output: $ java Planet 175 Your weight on MERCURY is Your weight on VENUS is Your weight on EARTH is …

Classes and inheritance Writing classes Manage inheritance Nested classes Enumerated types Annotations Generics

Annotations Annotations provide data about a program that is not part of the program such as naming the author of a piece of code or instructing the compiler to suppress specific errors An annotation has no effect on how the code performs Annotations use the and may be applied to a program's declarations: its classes, fields, methods, and so on The annotation appears first and often (by convention) on its own line, and may include optional arguments

class myClass() { } void MyMethod() { } there are three built-in annotations: and

Annotations import java.util.List; class Food {} class Hay extends Food {} class Animal { Food getPreferredFood() { return null; } document why the method was deprecated static void deprecatedMethod() { } } class Horse extends Animal { Horse() { return; Hay getPreferredFood() { return new Hay(); void useDeprecatedMethod() { Animal.deprecateMethod(); //deprecation warning - suppressed } }

Classes and inheritance Writing classes Manage inheritance Nested classes Enumerated types Annotations Generics

public class Library { private List resources = new ArrayList(); public void addMedia(Media x) { resources.add(x); } public Media retrieveLast() { int size = resources.size(); if (size > 0) { return resources.get(size - 1); } return null; } public class Media { } public class Book extends Media { } public class Video extends Media { } public class Newspaper extends Media { }

Generics //A Library containing only Books Library myBooks = new Library();... Book lastBook = (Book) myBooks.retrieveLast(); public class Library { private List resources = new ArrayList (); public void addMedia(E x) { resources.add(x); } public E retrieveLast() { int size = resources.size(); if (size > 0) { return resources.get(size - 1); } return null; } } Library myBooks = new Library ();... Book lastBook = myBooks.retrieveLast(); myBooks.addMedia(myFavoriteBook); // could generate error if // the input “myFavoriteBook” is not of Book type.

Generics Note: When compiling code that refers to generics, you might encounter a message like this: –Note: MyFile.java uses unchecked or unsafe operations. –Note: Recompile with -Xlint:unchecked for details. This error means that you have bypassed generics and have lost the benefit of compile-time type checking. You should fix your code to make full use of generics and take advantage of compile- time type checking.

Using generic types You'll usually see generics when dealing with collections of some kind When you specify the type of object stored in a collection: –The compiler can verify any operation that adds an object to the collection. –The type of an object retrieved from a collection is known, so there's no need to cast it to a type.

Using generic types Type Parameter Conventions: a type parameter is a single, uppercase letter — this allows easy identification and distinguishes a type parameter from a class name. – — Type – — for Type, when T is already in use – — Element (used extensively by the Java Collections Framework) – — Key – — Value – — Number You can invoke a generic type with any class, but you cannot invoke a generic type with a primitive type, such as int

Generics and relationships between types List ss = new ArrayList (1); List os = ss; //WRONG. This causes a compile error. But suppose that the above assignment was allowed and you then added an object to os: os.add(new Object()); If you later tried to retrieve the object from ss: ss.get(0); the Object that is returned isn't guaranteed to be a String — this clearly violates how ss was defined

Generics and type erasure When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method Type erasure means that Java applications that use generics maintain binary compatibility with Java libraries and applications created before generics Iterator is translated to type Iterator, which is called the raw type — a raw type is a class without a type argument. This means that you can't find out what type of Object a generic class is using at runtime

Generics and type erasure public class MyClass { public static void myMethod(Object item) { if (item instanceof E) { //Compiler error... } E item2 = new E(); //Compiler error E iArray[] = new E[10]; //Compiler error E obj = (E)new Object(); //Unchecked cast warning } The operations shown in red are meaningless at runtime because the compiler removes all information about the actual type argument (represented by the type param E) at compile-time. Type erasure exists so that new code may continue to interface with legacy code, but it should not otherwise be considered good programming practice

Wildcard types reverse(List list) The question mark is called the wildcard type. A wildcard represents some type, but one that is not known at compile time. In this case, it means that the reverse method can accept a List of any type. It might be a List of Integer, for example, or of String List is NOT the same as List Constrained with a lower bound In "List " the List must contain either Number s or Object s Constrained with an upper bound In "List " the List must contain Number s, Integer s, Long s, Float s or one of the other subtypes of Number

Using generic methods A generic method defines one or more type parameters in the method signature, before the return type: static void fill(List list, T obj) A type parameter is used to express dependencies between: –the types of the method's arguments –the type of the method's argument and the method's return type The type parameters are inferred from the invocation context, as in this example that calls the fill method: public static void main(String[] args) { List list = new ArrayList (10); for (int i = 0; i < 10; i++) { list.add(""); } String filler = args[0]; Collections.fill(list, filler);... }

Java language Object-Oriented Programming Concepts Language basics Object basics and simple data objects Classes and inheritance Interfaces and packages Common problems/solutions

Interfaces An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy; it defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior An interface is different from abstract class: –An interface cannot implement any methods, whereas an abstract class can. –A class can implement many interfaces but can have only one super-class. –An interface is not part of the class hierarchy. –Unrelated classes can implement the same interface

Interfaces All methods declared in an interface are implicitly public and abstract. An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Member declarations in an interface prohibit the use of some declarations; you cannot use transient, volatile, or synchronized in a member declaration in an interface. Also, you cannot use the private and protected specifiers when declaring members of an interface.

Package A package is a collection of related types providing access protection and name space management. Note that types refers to classes, interfaces, enums, and annotations You should bundle these classes and the interface in a package for several reasons, including the following: –You and other programmers can easily determine that these types are related. –You and other programmers know where to find types that can provide graphics-related functions. –The names of your types won't conflict with the type names in other packages because the package creates a new namespace. –You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the the package

Package naming By Convention: Companies use their reversed Internet domain name in their package names (for example, com.company.package ). Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.company.region.package ). In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to use an underscore.

Java language Object-Oriented Programming Concepts Language basics Object basics and simple data objects Classes and inheritance Interfaces and packages Common problems/solutions

Common problems Problem: The compiler complains that it can't find a class. –Make sure you've imported the class or its package. –Unset the CLASSPATH environment variable, if it's set. –Make sure you're spelling the class name exactly the same way as it is declared. Case matters! –If your classes are in packages, make sure that they appear in the correct subdirectory –Also, some programmers use different names for the class name from the.java filename. Make sure you're using the class name and not the filename. In fact, make the names the same and you won't run into this problem for this reason.

Common problems Problem: The interpreter says it can't find one of my classes. –Make sure you specified the class name--not the class file name--to the interpreter. –Unset the CLASSPATH environment variable, if it's set. –If your classes are in packages, make sure that they appear in the correct subdirectory –Make sure you're invoking the interpreter from the directory in which the.class file is located

Common problems The following is a list of common programming mistakes by novice Java programmers. –Did you forget to use break after each case statement in a switch statement? –Did you use the assignment operator = when you really wanted to use the comparison operator == ? –Are the termination conditions on your loops correct? Make sure you're not terminating loops one iteration too early or too late. That is, make sure you are using or >= as appropriate for your situation. –Remember that array indices begin at 0, so iterating over an array looks like this: for (int i = 0; i < array.length; i++)...

Are you comparing floating-point numbers using == ? Remember that floats are approximations of the real thing. The greater than and less than ( > and < ) operators are more appropriate on floating-point numbers. Make sure that blocks of statements are enclosed in curly brackets { }. The following code looks right because of indentation, but it doesn't do what the indents imply because the brackets are missing: for (int i = 0; i < arrayOfInts.length; i++) arrayOfInts[i] = i; System.out.println("[i] = " + arrayOfInts[i]); Are you using the correct conditional operator? Make sure you understand && and || and are using them appropriately. Do you use the negation operator ! Try to express condition without it. Doing so is less confusing and error-prone.

Are you using a do - while ? If so, do you know that a do - while executes at least once, but a similar while loop may not be executed at all? Are you trying to change the value of an argument from a method? Arguments in Java are passed by value and can't be changed in a method. Did you inadvertently add an extra semicolon ( ; ), thereby terminating a statement prematurely? Notice the extra semicolon at the end of this for statement: for (int i = 0; i < arrayOfInts.length; i++) ; arrayOfInts[i] = i;