1 / 32

Freshers Week Java Course Part 2

Freshers Week Java Course Part 2. An Introduction to Objects and Classes in Java Dr.-Ing. Norbert V ölker Lab Assistant: Roxanna Turner. Objects and Classes: Foundations. Procedural Programming. Procedural programming procedures that implement tasks

jag
Download Presentation

Freshers Week Java Course Part 2

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. Freshers Week Java Course Part 2 An Introduction to Objects and Classes in Java Dr.-Ing. Norbert Völker Lab Assistant: Roxanna Turner

  2. Objects and Classes: Foundations

  3. Procedural Programming • Procedural programming • procedures that implement tasks • sequence: read input, perform computations, change state, return output • Development • breakdown into smaller and smaller tasks • refinement • control structures: sequencing, if-then-else, … • Example • Rectangle area calculation

  4. Rectangle Area – Procedural Style public class RectangleArea { public static void main(String [] args) { double x1 = 1.0, y1 = 3.0, x2 = 3.0, y2 = 6.0; showRectangleArea(x1, y1, x2, y2); } public static void showRectangleArea(double x1, double y1, double x2, double y2) { double area = Math.abs((x2 - x1) * (y2 - y1)); System.out.println("Rectangle [(" + x1 + "," + y1 + "),(" + x2 + "," + y2 + ")] has area " + area); } }

  5. The Idea behind the OO Approach • Define objects and classes in programming by abstracting from real-world entities • a “class” is a category of objects • rectangles, cars, students, …, buffers, actions, … • an object is an element of a class • this rectangle, John’s car, a particular student, ... • models one particular entity • In Java, each object is an instance of exactly one class

  6. Class Diagram Rectangle class name Rectangle x1y1x2 y2 attributes (“data”, “state”) area()toString() methods

  7. Two Objects r1 : Rectangle r2 : Rectangle x1= 1.0; y1 = 3.0 x2 = 3.0 y2 = 6.0 x1 = -1.0 y1 = 2.0 x2 = -4.0 y2 = 1.0

  8. Object Identity and State • Every object has an identity • Corresponds to reality. • My car” is different from “your car” even if it has the same attributes (registration number, make, year, etc) • Objects have a state • Given by the current value of the attributes • Typically some attributes vary while others stay fixed • Class Rectangle might be used in a drawing program • coordinates can change as the rectangle is moved around, stretched or shrunk

  9. Methods • Methods allow • creation of objects, changing object state, finding out information about objects • methods can call other methods! • Class Rectangle currently only defines introspection methods • no methods for changing state as yet • add a method for moving rectangle horizontally public void moveX (double x) { …}

  10. OO Approach Remarks • Break system down into objects/classes • Your classes should model relevant aspects of reality • a “student” object in a Java program only reflects certain aspects of real students • you need to decide what aspects are needed in your program • Class definitions should aim for reusability • class Rectangle can be used in many different situations • include those methods which are expected by other developers who will be using your class

  11. The Beginnings of Programming with Objects and Classes in Java

  12. Using Objects in Java class Geometry { public static void main(String[] args) { Rectangle r1; // declaration of variable r1 = new Rectangle (1.0, 3.0, 3.0, 6.0); r1.moveX(-1.0); System.out.println(r1 + " has area " + r1.area()); } } Exercise: draw a class diagram for class Geometry.

  13. Assigning a New Object r1 = new Rectangle (1.0, 3.0, 3.0, 6.0); • creates a new Rectangle object by calling a “constructor” and assigns it to variable r1 • You can join a variable declaration with an assignment into a single “initialization” statement: Rectangle r1 = new Rectangle (1.0, 3.0, 3.0, 6.0); x1=1.0y1=3.0x2=3.0y2=6.0 r1

  14. Aliasing • Describe the effect of method call r1.moveX(-1.0); • Suppose we add the code below at the end of method Geometry.main() ? What would be output? Rectangle r2 = r1; System.out.println(r2); r1.moveX(1.0); System.out.println(r2); r1 = new Rectangle (0,0,0,0); System.out.println(r2);

  15. Encapsulation • We have used Rectangle objects without knowing about the implementation of the class. • This is an example of encapsulation • Information about how an object solves tasks is hidden inside the object. • Similar to “procedural abstraction” – you only need to know a procedure signature to call it, not how it is implemented.

  16. Implementation: Rectangle.java Attributes are also known as “instance variables” in Java public class Rectangle { double x1, x2, y1, y2; Rectangle (double x1, double y1, double x2, double y2) { …} double area() { … } public String toString() {… } public void moveX (double x) { …} }

  17. Attributes • Attributes are realized in Java as instance variables. • Also called the “fields” of the class. • The type of an instance variable can either be • one of the eight primitive types in Java (byte, short, int, long, float, double, char, boolean) or • a reference type • this is used to refer to objects

  18. Method Implementation double area() { return (Math.abs((x2 - x1) * (y2 - y1))); } public String toString() { return "Rectangle [(" + x1 + "," + y1 + "),(" + x2 + "," + y2 + ")]"; } public void moveX (double x) { x1 += x; x2 += x; } • Note the difference between parameters and attributes in method moveX(). • Do you know the meaning of “void” ?

  19. Constructors • For the code above to work, the Java class Rectangle must have a constructor method Rectangle (double x1, double y1, double x2, double y2) • The name of the constructor method is the same as the name of the class. • Same as the result type of the constructor. • In UML class diagrams, constructor methods are often not shown.

  20. Constructor Implementation Rectangle (double x1, double y1, double x2, double y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } • The use of “this” in order avoids a name clash between attributes and parameters. • Could also use parameter names that differ from attribute names.

  21. Static Attributes and Methods • Static attributes belong to the class, not particular objects • have the same value for each object of the class • For class Rectangle, we could add a static field count that is intialized with 0 and is incremented by 1 whenever a new rectangle is created. • Static methods (also called “class” methods) do not refer to a particular object. public static double sqrt(double number) double sqrtTwo = Math.sqrt(2); //usage • Question: normal “instance method” call or static call? System.out.println("Now Sort Array"); Arrays.sort(ray);

  22. Constants • It is bad programming style to use hard coded numbers in your code. if (numberOfStudents > 100) { ….}; • It is better to use variables, for example: double maxCourseSize = 100; if (numberOfStudents > maxCourseSize) { …} • Constants can be declared as static final fields in a class. This protects against unwanted changes. public static final maxCourseSize = 100; • From outside the class, access needs a prefix: double circumference = Math.PI * 2 * radius;

  23. Null • A variable of a reference type may be set to null. This means that it does not refer to any object. if (errorInInput) Student nextStudent = null; • You can check if the current value of a variable is null. • This is useful as some methods return null if they are not able to return a valid object. For example, showInputDialog returns null if the user hits the “Cancel” button. String input = JOptionPane.showInputDialog( “Please enter account number”); if (input == null) …

  24. Packages Libraries and code organisation.

  25. Java Library Packages • Java library classes are organised in packages. http://java.sun.com/javase/6/docs/api/ • Examples: java.lang,java.util, java.net, java.util.regex javax.swing … • java.lang entities are automatically known to the compiler. • The full name of class String is java.lang.String • The large number of libraries in J2SE is one of the main reasons behind the popularity of Java. • Exercises will make use of classes in java.util : • Random • and possibly ArrayList and TreeSet

  26. Import Statements • The import statement makes classes accessible without having to use the full long name, for example: import java.util.Random class TestRandom { public static void main (String[]args) { Random rGen = new Random(seed); …} } • Import statements must be placed before any class declarations in the .java file,. • A file can have several import statements. • You can also import all classes from a package in one go: import java.util.*

  27. More on Import • Care has to be taken that this does not lead to a collision: different packages might contain classes with the same name. • Example [Eckel]: import com.bruceeckel.simple.*; import java.util.*; The compiler will complain in this case if you try to create a new object of class Vector as it does not know which Vector class is meant. • Without the import, there is no clash: java.util.Vector x = new java.util.Vector();

  28. Packages and Directory Structure • All the .class files belonging to one package need to be in the same directory. • The directory structure needs to correspond to the package structure • For a package called “freshersWeek”, the files should be in directory “freshersWeek” • For a package “ce832.exercises”, there should be a directory “ce832” with a subdirectory “exercises”. • etc.

  29. Packages: Compiling and Running • In order to compile from the command prompt, change to the root directory of the package. cd /ufs/csstaffc/users/norbert/src/ javac ce832/utilities/*.java • Running method ce832.utilities.MyRandom.main(): java ce832.utilities.MyRandom • For usage of the CLASSPATH environment variable, see the online Java tutorial, section packages. • Check out Java IDEs (NetBeans, Eclipse, IntelliJ, …) • many advantages • do not move source files on the disk while the IDE is running (use IDE refactor/renaming instead)

  30. Organising your Own Classes • It is easiest to put all your java source files into one directory and compile them with: javac *.java • BUT: putting all files into one directory is bad practice for larger projects. • Use packages in order to group classes together. package ce832.utilities; public class MyRandom { // … • The package declaration needs to be right at the start of the .java file.

  31. Java Collections are Generic • Java API Documentation • Class ArrayList<E> • Class TreeSet<E> • These are generic classes • Type variable E stands for the collection elements • Can be substituted with other types in applications • For example, you could have • ArrayList<Integer> • ArrayList<ArrayList<Boolean>> • TreeSet<ArrayList<TreeSet<Integer>>> • ...

  32. Literature • Online Java Tutorial http://java.sun.com/docs/books/tutorial/ • Cay Horstmann, Big Java, Wiley. • H.M. Deitel and P.J. Deitel: Java – How to program, • Bruce Eckel: Thinking in Java (Online available) • And many others! • Java 5 saw significant changes to the language, in particular the introduction of generics. • Differences between Java 6 and Java 5 are mainly on the level of libraries and implementation improvements. • The Java API documentation is your friend http://java.sun.com/javase/6/docs/api/

More Related