1 / 173

Object-Oriented Programing in Java

Object-Oriented Programing in Java. Cheng-Chia Chen. Contents. Object and Class The contents of an object/class Creating and initializing Objects Accessing object data and methods Destroying and finalizing objects Subclass and inheritance Interfaces Java modifiers summary.

nirav
Download Presentation

Object-Oriented Programing 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. Object-Oriented Programing in Java Cheng-Chia Chen

  2. Contents • Object and Class • The contents of an object/class • Creating and initializing Objects • Accessing object data and methods • Destroying and finalizing objects • Subclass and inheritance • Interfaces • Java modifiers summary

  3. What is an Object ? • Real-world objects: • Concrete objects: Apple1, Car1, TV2, Teacher2, Student3, … • Conceptual Objects: 1, 2.3, Date1, Meeting2, point2, … • Objects have: • Properties (attributes): color, weight, height, sex, name, speed, position,… • Capabilities (behaviors): can receive commands(, request, query) and respond (do actions) based on its internal states to change its internal state and/or external environment. • The properties of an object constitutes its current state.

  4. What is a Software object ? • a software bundle of data and functions used to model real-world objects you find in everyday life. • In OOP, Software objects are building block of software systems • program is a collection of interacting objects • objects cooperate to complete a task • to do this, they communicate by sending “messages” to each other • Software objects can model • tangible things: School, Car, Bicycle, • conceptual things: meeting, date • Processes: finding paths, sorting cards • Note: Software objects are only abstraction of real-worldobjects; properties and behavior of irrelevance will not be modeled in software objects.

  5. What is a Java Object? • In Java, an object consists of 0 or more fields and 0 or more methods. • Fields are used to model properties. • Methods are used to model capabilities. • Fields are variables. • like the fields of a C struct. • An object without methods is equivalent to a C struct. • A method is similar to a C function. • Normally, it will operate on the fields of the object. • These fields are accessible by name in the method. • Java variables can not hold objects, only references to them. • Object do not have a names. • Object are created only at runtime. • Given a reference r to an object, the syntax for accessing a field is: r.field_name, the syntax for accessing a method is: r.method()

  6. Classes and Objects • Current conception: • a java/software object  a real-life object, • e.g., a Java car  a real car • Disadvantage: impractical to work with objects this way • may be indefinitely many (i.e., modeling all atoms in the universe) • do not want to describe each individual separately, because they may have much in common • Classifying objects into classes of similar properties/behaviors • factors out commonality among sets of similar objects • lets us describe what is common once • then “stamp out” any number of copies later • Ex: Student: { S1, S2, S3 } Course:{C1,C2,C3} Teacher:{ T1,T2} • but not {s1, t1}, {s2, t2}, {c1,c2,c3,s3} • Analog: • stamp 印章 (class) • Imprints 戳印 (objects)

  7. What is a Java Class? • In Java, a class is a template (textual description) of a set of similar objects. • All objects in the class have the same types of properties and the same set of capabilities. • It defines the fields and methods that all objects in that class will have. • Classes have names. • Class appear in the text of your program. • A java program consists of a set of classes. • A defined class is a Java Type, so you can have objects or variables of that type.

  8. Class diagrams

  9. An Example: the class of Circles: • Properties: a circle can be described • by the x, y position of its center and • by its radius. • Methods: Some useful operations on Circles: • compute circumference, • compute area, • check whether points are inside the circle, • etc.

  10. The Circle class • By defining the Circle class (as below), we create a new data type. // The class of circles (partially defined) class Circle {// Fields double x, y; double r; // Methods double circumference() { return 2 * 3.14159 * r; } double area() { return 3.14159 * r * r ; } void scale(double multiplier) { r *= multiplier; } void print() { System.out.println("circle of radius "+ r + " with center at (" + x + "," + y + ")“ ); } }

  11. Creating Objects • In Java, objects are created by the new operator. • For example: //define a variable to refer to Circle objects;no objects yet. Circle c ; // c is null now // create a circle object and make the variable refer to it c = new Circle(); // define variable and create Circle object all at once Circle d = new Circle(); Note: the fields in these objects are given default values at creation (0 for numbers; null for object references)

  12. Accessing Object Data • We can access data fields of an object (subject to visibility restrictions -- see later). • For example: // create a new Circle Circle c = new Circle(); //initialize our circle to have center (2, 5) and radius 1.0. c.x = 2.0; c.y = 5.0; c.r = 1.0; // create another circle Circle d = new Circle(); //initialize this circle to have center (10,7)and double the radius of circle c. d.x = 10.0; d.y = 7.0; d.r = c.r * 2.0;

  13. Using Object Methods • To access the methods of an object, use same syntax as accessing the data of an object: Circle c; double a; ... a = c.area(); // Not a = area(c); Notes • Each method has a signature, which is defined by: • The method name and • The sequence of all types of arguments • Each class can define several methods with same name and different types of arguments (overloading).

  14. Constructors • Every class in Java has at least one constructor method, which has the same name as the class. • The purpose of a constructor is to perform any necessary initialization for new objects. • Java provides a default constructor that takes no arguments and performs no special initialization (i.e. gives objects default values). • Note: Java compiler provide the default constructor: className() only if you do not provide any constructor at your class definition. • For example: Circle c = new Circle();

  15. Defining a Constructor • Can define additional constructors for initialization. // The circle class, with a constructor public class Circle { public double x, y, r; // Constructor method public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; } // Other methods ... as above ... }

  16. Defining a Constructor (cont.) • With the new constructor, we can create and initialize a Circle object as: Circle c = new Circle(2.0, 5.0, 1.0); • A constructor is like a (static) method whose name is the same as the class name. • The return value is an instance of the class. • No return type is specified in constructor declarations, nor is the void keyword used.

  17. Multiple Constructors • A class can have any number of constructor methods. public class Circle { public double x, y, r; // Constructors public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; } public Circle(double r) { x = 0.0; y = 0.0; this.r = r; } public Circle(Circle c) { this.x = c.x; this.y = c.y; this.r = c.r; } public Circle() { x = 0.0; y = 0.0; r = 1.0; } // Other methods ... as above ... }

  18. Multiple Constructors (cont.) • With the new constructors, we can initialize circle objects as follows: Circle c1 = new Circle(2.0, 5.0, 1.0); // c1 contains (2.0, 5.0, 1.0) Circle c2 = new Circle(3.5); // c2 contains (0.0, 0.0, 3.5) Circle c3 = new Circle(c2); // c3 contains (0.0, 0.0, 3.5) Circle c4 = new Circle(); // c4 contains (0.0, 0.0, 1.0) • All uninitialized data receives default values.

  19. Invoking one constructor from another • We can use this(…) in a constructor to invoke other constructor. public class Circle { public double x, y, r; // Constructors public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; } public Circle(double r) //{x =0.0; y = 0.0; this.r = r;} replaceable by {this(0.0,0.0,r); } public Circle() //{x = 0.0; y = 0.0; r = 1.0;} replaceable by {this(1.0); } ... } Note: do not result in recursion.

  20. bishop1 Object and Object References • A java object is a memory structure containing both data and methods • An object reference holds the memory address of an object • Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an object ChessPiece bishop1 = new ChessPiece();

  21. Before After num1 num1 num2 num2 5 5 12 5 Assignment Revisited • The act of assignment takes a copy of a value and stores it in a variable • For primitive types: int num1 = 5, unm2 = 12; num2 = num1;

  22. After Before bishop1 bishop2 bishop1 bishop2 Reference Assignment • For object references, assignment copies the memory location: bishop2 = bishop1;

  23. Aliases • Two or more references that refer to the same object are called aliases of each other • One object (and its data) can be accessed using different variables • Aliases can be useful, but should be managed carefully • Changing the object’s state (its variables) through one reference changes it for all of its aliases • Ex: Circle c = new Circle(1.0, 2.0, 3.0); Circle d = c; // c and d are aliases. c.r = 4.0; // d.r == 4.0 now.

  24. Destroying Objects • When an object no longer has any valid references to it, it can no longer be accessed by the program • It is useless, and therefore called garbage • Java performs automatic garbage collection periodically, returning an garbage object's memory to the system for future use • Hence it is needless to explicitly destroy objects. • How can references to objects '' go away'‘ ? • Re-assigning object variables (a = b; a = null) or • object variables (locals or parameters) going out of scope. • no more malloc/free bugs

  25. Object Finalization • A constructor method performs initialization for an object; a Java finalizer method performs finalization for an object. • Garbage collection only help freeing up memory. • But there are other resources needed to be released. • file descriptors, sockets, lock, database connection.

  26. Example: A Finalizer Method from the Java FileOutputStream class. /** * Closes the stream when garbage is collected. * Checks the file descriptor first to make sure it is not already closed. */ protected void finalize() throws IOException { if (fd != null) close(); }

  27. Notes about finalize() • invoked before the system garbage collects the object. • no guarantees about when a finalizer will be invoked, or in what order finalizers will be invoked, or what thread will execute finalizers. • After a finalizer is invoked, objects are not freed right away. • because a finalizer method may "resurrect" an object by storing the this pointer somewhere. • may throw an exception; If an uncaught exception actually occurs in a finalizer method, the exception is ignored by the system. • No ‘class Finalization’ method defined.

  28. Classes v.s. Objects • two of the most frequently occurring terms in the OO programmer's vocabulary. • A class An object... • exist at compile time exists at runtime only • a template/pattern created/instantiated from for objects a class' specification • "only exists once" can be created many times from one class • a .java file returned by the new operator • dress pattern dress • architectural plans house • stamp imprints

  29. Types of variables and methods in a Java class • There are two main types of variables/fields: • instance variables • class (or static) variables • Instance variables store information pertaining to one particular object's state • Class variables store information pertaining to all objects of one class • Likewise, there are two types of methods: • Instance methods • Class (static) methods • Instance methods belong to individual objects; whereas class methods belongs to the whole class. • Note: In class method, you cannot use this and instance variables.(why?)

  30. Class diagram of an Account class. Class Name Instance Methods ShowNumberOfAccount Class Methods

  31. Declare class field/method with the ‘static’ Modifier • makes methods and variablesbelong to the class rather than instances of the class. • Example: counting how many circles: public class Circle { public double x, y, r; // instance variables // ncircles is class variable public static int ncircles = 0; // Constructors public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; ncircles++; } public Circle(double r) { x = 0.0; y = 0.0; this.r = r; ncircles++; } ...}

  32. The static Modifier (cont.) • In the above example, there's only one instance of the ncircles variable per Circle class but one instance of x, y and r per Circle object. • Diff. ways to referencencircles: • Circle.ncircles // ClassName.classVarName • ncircles; this.ncircles, // used inside the Circle class definition only • c.ncircles // where c is a Circle variable • Similar approach for static methods. • Examples of static methods (or called class method): • Math.cos(x) Math.pow(x,y) Math.sqrt(x)

  33. Notes on class methods • Must be declared with the static keyword • Also called static method • Can only operate on class variables (e.g., static) • Cannot use ‘this’ • Cannot use instance variables • To access a class method: same as to access class vars: • Circle.countCircles() // ClassName.classVarName • countCircles(); this.countCircles(), • // legal only when inside the Circle class definition • c.countCircles() // where c is a Circle variable • Lots of examples of class methods in the JDK (e.g., String)

  34. Class B { int x; static int y; static int b1() { … } int b2 () { … } static int b3() { … // class method int c; c = x; c = this.y //error c = y; c = B.y; //ok! A a = new A(); B b = new B(); c = a.a1(); //ok! c = a.a2() ; // ok! c = A.a2() ; // error! c = A.a1() ; // ok! c = b.b1() ; //ok! c = b.b2() ; // ok! c = B.b2() ; // error! c = B.b1() ; // ok! c = b1(); // ok c = b2(); // error } Int b4() { // instance method c = x; c = this.x //ok! c = y; c = B.y; c = this.y //ok! … c = b1(); c = this.b1() // ok c = b2(); c=this.b2() // ok } } Class A { public static int a1(){…} public int a2() {…} … } Example: instance member v.s. class member

  35. Class and Instance initializers • Both class and instance variables can have initializers attached to their declarations. • static int num_circles = 0; • float r = 1.0; • Class variables are initialized when the class is first loaded. • Instance variables are initialized when an object is created. • Sometimes more complex initializationis needed. • For instance variables, there are constructor methods ,and instance initializer. • For class variables static initializers are provided

  36. An example static/instance initializer public class TrigCircle { // Trigonometric circle // Here are our static lookup tables, and their own simple initializers. static private double sin[] = new double[1000]; static private double cos[] = new double[1000]; // Here's a static initializer "method" that fills them in. // Notice the lack of any method declaration! static { double x, delta_x; int i; delta_x = (Circle.PI/2)/(1000-1); for(i = 0, x = 0.0; i < 1000; i++, x += delta_x) { sin[i] = Math.sin(x); cos[i] = Math.cos(x); } … // The rest of the class omitted.

  37. An example static/instance initializer (continued) // instance field and methods Private int[] data = new int[100]; // data[i] = i for i = 0..99 // instance initializer as an unnamed void method { for(int I = 0; I <100; I++) data[I] = I; } … }

  38. Notes on initializers • can have any number of static/instance initializers; • can appear anywhere a field or method can appear. • Static initializer behaves like class method and cannot use this keyword and any instance fields of the class • The body of each instance initializers (alone with field initialization expressions) is executed in the order they appear in the class and is executed at the beginning of every constructor. • The body of each static initializers (alone with static field initialization expressions) is executed in the order they appear in the class and is executed while the class is loaded.

  39. Inheritance in OOP • Inheritance is a form of software reusability in which new classes are created from the existing classes by absorbing their attributes and behaviors. • Instead of defining completely (separate) new class, the programmer can designate that the new class is to inherit attributes and behaviours of the existing class (called superclass). The new class is referred to as subclass. • Programmer can add more attributes and behaviors to the subclass, hence, normally subclasses have more features than their superclasses. • Inheritance relationships form tree-like hierarchical structures.

  40. Subclasses and Inheritance • An important aspect of OO programming: • the ability to create new data types based on existing data types • Example ... a class of drawable Circles: • we'd like to be able to draw the circles we create, as well as setting and examining their properties. • for drawing, we need to know the color of the circle's outline and its body • In Java, we implement this by defining a new class that extends the behavior of the Circle class. • This new class is a subclass of Circle.

  41. Subclass Example • The class GraphicCircle: public class GraphicCircle extends Circle { // Extra fields Color outline, fill; // Extra constructors public GraphicCircle(Color edge, Color fill) { x = 0.0; y = 0.0; r = 1.0; outline = edge; this.fill = fill; } public GraphicCircle(double r, Color edge, Color fill) { super(r); outline = edge; this.fill = fill; } // Extra methods public void draw(Graphics g) { g.setColor(outline); g.drawOval(x-r, y-r, 2*r, 2*r); g.setColor(fill); g.fillOval(x-r, y-r, 2*r, 2*r); } }

  42. Subclass Inheritance • A subclass inherits fields and methods from its parent class. • A subclass methodoverridesa superclass method if they have the same signature. • A subclass field shadows a superclass field if they have the same name. • Refer to the superclass field via super.field • Note: you can also use super.method(…) to refer to overridden superclass method.

  43. Using Subclasses • Subclasses are just like ordinary classes: GraphicCircle gc = new GraphicCircle(); ... double area = gc.area(); • We can assign an instance of GraphicCircle to a Circle variable. • Example: GraphicCircle gc; ... ... Circle c = gc; //widening conversion is // always safe; explicit cast is not needed.

  44. Superclasses, Objects, and the Class Hierarchy • Every class has a superclass. • If a class has no extends clause, it extends the Object class. • Object Class: • the only class that does not have a superclass • methods defined by Object can be called by any Java object

  45. Abstract Classes • Abstract class allows us to declare methods without implementation. • the unimplemented method is called an abstract method. • Subclasses can extend abstract class and provide implementation of all or portion of abstract methods. • The benefit of an abstract class is that • methods may be declared such that the programmer knows the interface definition of an object, • however, methods can be implemented differently in different subclasses of the abstract class.

  46. Abstract Classes (cont.) • Any class containing anabstract methodis automatically abstract itself • But an abstract class need nothave abstract methods in it! • an abstract class can not be instantiated • a subclass of an abstract classcan be instantiatedif it overrides each of the abstract methods of itssuperclass andprovides an implementation for all of them • if a subclass of an abstract classdoes not implement all of the abstract methodsit inherits, thatsubclass is itself abstract

  47. Abstract Classes (cont.): an example public abstract class Shape { public abstract double area(); // abstract methods // to be implemented by subclasses public abstract double circumference(); } public class Circle extends Shape { protected double r; protected static final double PI=3.141592653; public double Circle() { r = 1.0; } public double Circle(double r) { this.r = r; } // implementation of two abstract methods of shape class public double area(){ return PI*r*r; } public double circumference() { return 2*PI*r; } public double getRadius() { return r; } }

  48. Abstract Classes : an example (cont.) public class Rectangle extends Shape { protected double w,h; // two constructors public Rectangle() { w=1.0; h=1.0; } public Rectangle(double w, double h) { this.w = w; this.h = h; } // implementation of two parent methods public double area() { return w*h; } public double circumference() { return 2*(w + h); } // methods for this class public double getWidth() { return w; } public double getHeight() { return h; } }

  49. Inheritance revisited • the concept of inheritance • the protected modifier • adding and modifying methods through inheritance • creating class hierarchies 1

  50. Inheritance • Inheritance allows a software developer to derive a new class from an existing one • The existing class is called the parent class, or superclass, or base class • The derived class is called the child class or subclass. • The child class inherits characteristics (data & methods) of the parent class • That is, the child class inherits the methods and fields defined for the parent class 2

More Related