CMSC 341 Java Review. 08/03/2007 CMSC 341 Java Review 2 Important Java Concepts and Terminology JRE is the Java Runtime Environment and it creates a virtual.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Outline Java program structure Basic program elements
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
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.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Polymorphism & Interfaces
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
The Java Programming Language
CMSC 341 Inheritance and the Collection classes. 8/03/2007 UMBC CMSC 341 Java 3 2 Inheritance in Java Inheritance is implemented using the keyword extends.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
JAVA BASICS Prepared by The Smartpath Information Systems
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Introduction to Generics
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
1 Chapter 4 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
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.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
1 Chapter 2 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Classes Revisited Chapter 8.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
A Concrete Presentation on Abstract Classes and Methods, Interfaces, and Polymorphism CSC 202.
JAVA MULTIPLE CHOICE QUESTION.
Chapter 11 Inheritance and Polymorphism
Java Primer 1: Types, Classes and Operators
Internet and Java Foundations, Programming and Practice
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Applying OO Concepts Using Java
CMSC 202 Generics.
Chapter 8 Class Inheritance and Interfaces
Chapter 11 Inheritance and Polymorphism Part 2
Presentation transcript:

CMSC 341 Java Review

08/03/2007 CMSC 341 Java Review 2 Important Java Concepts and Terminology JRE is the Java Runtime Environment and it creates a virtual machine within your computer known as the JVM (Java Virtual Machine). JRE is specific to your platform and is the environment in which Java byte code is run. JDK (formerly SDK) is the Java Development Kit. JDK = JRE + development tools JavaSE is the Java Platform Standard Edition, which you will be using in this course to build stand alone applications. To learn more about JDK, JRE, etc., visit

08/03/2007 CMSC 341 Java Review 3 Running and Compiling Java Java Code Java Bytecode JRE for Linux JRE for Windows Java compiler Hello.java javac Hello.java Hello.class java Hello Java interpreter translates bytecode to machine code in JRE JRE contains class libraries which are loaded at runtime.

08/03/2007 CMSC 341 Java Review 4 Important Java Concepts Everything in Java must be inside a class. Every file may only contain one public class. The name of the file must be the name of the class appended to the java extension. Thus, Hello.java must contain one public class named Hello.

08/03/2007 CMSC 341 Java Review 5 Methods in Java The main method has a specific signature. Example: “Hello world!” Program in Java public class Hello { public static void main(String args[]) { System.out.println(“Hello world!”); } Notice no semi-colon at the end!

08/03/2007 CMSC 341 Java Review 6 Methods in Java (cont.) All methods must be defined inside a class. Format for defining a method: [modifiers] return_type method_name([param_type param]*) { statements; } For main, modifiers must be public static, return type must be void, and the parameter represents an array of type String, String []. This parameter represents the command line arguments when the program is executed. The number of command line arguments in the Hello program can be determined from args.length.

08/03/2007 CMSC 341 Java Review 7 Data Types There are two types of data types in Java – primitives and references. Primitives are data types that store data. References store the address of an object, which is encapsulated data. int x = 5;Date d = new Date(); 5 x int d FEO3 Date ref Date obj FEO3

08/03/2007 CMSC 341 Java Review 8 Arrays Arrays in Java are objects. The first line of code creates a reference for an array object. The second line creates the array object. int [] arrayRef; arrayRef = new int[5]; arrayRef[2] = 5; All arrays have a length property that gives you the number of elements in the array.  args.length is determined at runtime int [ ] ref arrayRef DFO7 Array obj DFO

08/03/2007 CMSC 341 Java Review 9 Arrays (cont.) An array of objects is an array of object references until the objects are initialized. Point pArray [] = new Point[5]; pArray[2] = new Point(); Point [ ] ref pArray CDO8 Array obj CDO8 null AB12 null AB12 Point obj

08/03/2007 CMSC 341 Java Review 10 Multidimensional Arrays A pictorial rendition of twodim2. int [ ] [ ] ref twodim2 Array obj of array refs Array obj Each element is an int [] ref

08/03/2007 CMSC 341 Java Review 11 Java Naming Conventions Classes and Interfaces StringBuffer, Integer, MyDate Identifiers for methods, fields, and variables _name, getName, setName, isName, birthDate Packages java.lang, java.util, proj1 Constants PI, MAX_NUMBER

08/03/2007 CMSC 341 Java Review 12 Comments Java supports three types of comments.  C style /* multi-liner comments */  C++ style // one liner comments  Javadoc /** This is an example of a javadoc comment. These comments can be converted to part of the pages you see in the API. */

08/03/2007 CMSC 341 Java Review 13 Access Control private default protected public Modifier Same class Same package Subclass Universe

08/03/2007 CMSC 341 Java Review 14 Access Control for Classes Classes may have either public or package accessibility. Only one public class per file. Omitting the access modifier prior to class keyword gives the class package accessibility.

08/03/2007 CMSC 341 Java Review 15 Classes In Java, all classes at some point in their inheritance hierarchy are subclasses of java.lang.Object, therefore all objects have some inherited, default implementation before you begin to code them.  String toString()  boolean equals(Object o)

08/03/2007 CMSC 341 Java Review 16 Inheritance in Java Inheritance is implemented using the keyword extends. public class Employee extends Person { //Class definition goes here – only the //implementation for the specialized behavior } A class may only inherit from only one superclass. If a class is not derived from a super class then it is derived from java.lang.Object. The following two class declarations are equivalent: public class Person {…} public class Person extends Object {…}

08/03/2007 CMSC 341 Java Review 17 Polymorphism If Employee is a class that extends Person, an Employee “is-a” Person and polymorphism can occur. Person [] p = new Person[2]; p[0] = new Employee(); p[1] = new Person(); Creates an array of Person references

08/03/2007 CMSC 341 Java Review 18 Polymorphism (cont.) However, a Person is not necessarily an Employee. The following will generate a compile-time error. Employee e = new Person(); Polymorphism requires general class on left of assignment operator, and specialized class on right. Casting allows you to make such an assignment provided you are confident that it is ok. public void convertToPerson(Object obj) { Person p = (Person) obj; }

08/03/2007 CMSC 341 Java Review 19 Abstract Classes and Methods Java also has abstract classes and methods. If a class has an abstract method, then it must be declared abstract. public abstract class Node{ String name; public abstract void type(); public String toString(){ return name;} public Node(String name){ this.name = name; } Abstract methods have no implementation.

08/03/2007 CMSC 341 Java Review 20 More about Abstract Classes Abstract classes can not be instantiated. // OK because n is only a reference. Node n; // OK because NumberNode is concrete. Node n = new NumberNode(“Penta”, 5); // Not OK. Gives compile error. Node n = new Node(“Name”);

08/03/2007 CMSC 341 Java Review 21 Inner Classes It’s possible to define a class within another class definition. This is called an inner class and is a technique we’ll use in this course. There are many reasons to define an inner class and many rules regarding inner classes. For our purposes, we’re interested in code-hiding. Users of the outer class can’t access a private inner class. The inner class has a “link” to the outer class.  The inner class can access members of the outer class

08/03/2007 CMSC 341 Java Review 22 Inner Class Example public class Package { private boolean rushOrder; private String label; private class Contents { private int value; public Contents (int value) {this.value = value;} public int getValue( ) { return value; } } private class Destination { private String address; public Destination( String whereTo ){ address = whereTo; } public String getAddress( ) { return addres; } public String toString( ) { return label + “sent to “ + address; }

08/03/2007 CMSC 341 Java Review 23 Interfaces An interface is like class without the implementation. It contains only  public, static and final fields, and  public and abstract method headers (no body). A public interface, like a public class, must be in a file of the same name.

08/03/2007 CMSC 341 Java Review 24 Interface Example The methods and fields are implicitly public and abstract by virtue of being declared in an interface. public interface Employable { void raiseSalary(double d); double getSalary(); }

08/03/2007 CMSC 341 Java Review 25 Interfaces (cont.) Many classes may implement the same interface. The classes may be in completely different inheritance hierarchies. A class may implement several interfaces. public class TA extends Student implements Employable { /* Now TA class must implement the getSalary and the raiseSalary methods here */ }

08/03/2007 CMSC 341 Java Review 26 The Collections Framework Is a collection of interfaces, abstract and concrete classes that provide generic implementation for many of the data structures you will be learning about in this course.

08/03/2007 CMSC 341 Java Review 27 Generics Since JDK 1.5 (Java 5), the Collections framework has been parameterized. A class that is defined with a parameter for a type is called a generic or a parameterized class. If you compare the Collection interface in the API for to the one in version 1.5.0, you will see the interface is now called Collection.

08/03/2007 CMSC 341 Java Review 28 Collection Interface The E represents a type and allows the user to create a homogenous collection of objects. Using the parameterized collection or type, allows the user to retrieve objects from the collection without having to cast them. Before: List c = new ArrayList(); c.add(new Integer(34)); Integer i = (Integer) c.get(0); After: List c = new ArrayList (); c.add(new Integer(34)); Integer i = c.get(0);

08/03/2007 CMSC 341 Java Review 29 Implementing Generic Classes In the projects for this course, you will be implementing your own parameterized generic classes. The Cell class that follows is a small example of such a class.

08/03/2007 CMSC 341 Java Review 30 Generic Cell Example public class Cell { private T prisoner; public Cell( T p) { prisoner = p; } public T getPrisoner(){return prisoner; } } public class CellDemo { public static void main (String[ ] args) { // define a cell for Integers Cell intCell = new Cell ( new Integer(5) ); // define a cell for Floats Cell floatCell = new Cell ( new Float(6.7) ); // compiler error if we remove a Float from Integer Cell Float t = (Float)intCell.getPrisoner( ); System.out.println(t); }

08/03/2007 CMSC 341 Java Review 31 Dont’s of Generic Programming You CANNOT use a type parameter in a constructor. T obj = new T(); You CANNOT create an array of a generic type. T [] array = new T[5 ];

08/03/2007 CMSC 341 Java Review 32 Do’s of Generic Programming The type parameter must always represent a reference data type. Class name in a parameterized class definition has a type parameter attached. class Cell The type parameter is not used in the header of the constructor. public Cell( ) Angular brackets are not used if the type parameter is the type for a parameter of the constructor. public Cell3(T prisoner ); However, when a generic class is instantiated, the angular brackets are used List c = new ArrayList ();

08/03/2007 CMSC 341 Java Review 33 The Arrays class The java.util.Arrays class is a utility class that contains several static methods to process arrays of primitive and reference data.  binarySearch – searches sorted array for a specific value  equals – compares two arrays to see if they contain the same elements in the same order  fill – fills an array with a specific value  sort – sorts an array or specific range in array in ascending order according to the natural ordering of elements

08/03/2007 CMSC 341 Java Review 34 Natural Order The natural order of primitive data types is known. However, if you create an ArrayList or Array of some object type, how does the sort method know how to sort the array? To be sorted, the objects in an array must be comparable to each other.

08/03/2007 CMSC 341 Java Review 35 The Comparable Interface The Comparable interface defines just one method to define the natural order of objects of type T public interface java.lang.Comparable { int compareTo(T obj); } compareTo returns  a negative number if the calling object precedes obj  a zero if they are equal, and  a positive number if obj precedes the calling object

08/03/2007 CMSC 341 Java Review 36 Comparable Example import java.util.*; public class Fraction implements Comparable { private int n; private int d; public Fraction(int n, int d){ this.n = n; this.d = d;} public int compareTo(Fraction f) { double d1 = (double) n/d; double d2 = (double)f.n/f.d; if (d1 == d2) return 0; else if (d1 < d2) return -1; return 1; } public String toString() { return n + “/” + d; } } Casting required for floating point division

08/03/2007 CMSC 341 Java Review 37 Sort Example public class FractionTest { public static void main(String []args) { Fraction [] array = {new Fraction(2,3), new Fraction (4,5), new Fraction(1,6); Arrays.sort(array); for(Fraction f :array) System.out.println(f); }

08/03/2007 CMSC 341 Java Review 38 Bounding the Type You will see in the API a type parameter defined as follows. This restricts the parameter to representing only data types that implement E, i.e. subclasses of E boolean addAll(Collection c)

08/03/2007 CMSC 341 Java Review 39 Bounding Type Parameters The following restricts the possible types that can be plugged in for a type parameter T. public class RClass > " extends Comparable " serves as a bound on the type parameter T. Any attempt to plug in a type for T which does not implement the Comparable interface results in a compiler error message

08/03/2007 CMSC 341 Java Review 40 More Bounding In the API, several collection classes contain in the constructor. This bounds the parameter type to any class that is a supertype of T. TreeSet(Comparable c)

08/03/2007 CMSC 341 Java Review 41 Generic Sorting public class Sort { public static > void bubbleSort(T[] a) { for (int i = 0; i< a.length - 1; i++) for (int j = 0; j < a.length -1 - i; j++) if (a[j+1].compareTo(a[j]) < 0) { T tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; }

08/03/2007 CMSC 341 Java Review 42 Generic Sorting (cont.) Given the following: class Animal implements Comparable {...} class Dog extends Animal {... } class Cat extends Animal {... } Now we should be able to sort dogs if contains the compareTo method which compares animals by weight. BUT… bubblesort only sorts objects of type T which implements Comparable. Here the super class implements Comparable…. HENCE, we can’t use bubblesort for Cats or Dogs New and improved sort on next page can handle sorting Dogs and Cats.

08/03/2007 CMSC 341 Java Review 43 Generic Sorting (cont.) public class Sort { public static > void bubbleSort(T[] a) { for (int i = 0; i< a.length - 1; i++) for (int j = 0; j < a.length -1 - i; j++) if (a[j+1].compareTo(a[j]) < 0) { T tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; }