Defining Classes. The basic syntax for defining a class in Java is: class <class-name> [<data-declarations>] [<class-constructors>] [<methods>]
|
|
- Clyde Shepherd
- 6 years ago
- Views:
Transcription
1 Defining Classes As well as using predefined library classes in Java programs, it is usual to define new classes as well. The library classes model commonly occurring situations, the new classes are used for situations unique to a given program. The basic syntax for defining a class in Java is: class <class-name> [<data-declarations>] [<class-constructors>] [<methods>] where <class-name> is the name of the class,a legal Java identifier; <data-declarations> is one or more class and/or instance variable declarations; <class-constructors> is one or more Constructors, and<methods> is one or more class and/or instance method declarations.
2 Simple Classes: The simplest sort of Java class contains only instance variables. This sort of class is analogous to the struct in C: Complex.java public class Complex { public double r, // real part i; // imaginary part This defines a new type called Complex with two publicly accessible data members, r and i. Note that the class definition occurs in a file called Complex.java. This is mandatory for public classes: each such class must be defined in a file which has the same name as the class (and filename extension.java.) Only one public class definition is allowed per file.
3 Once the class is defined, it may be used in other Java source files exactly like any other class: // Declare and create a Complex value. // Complex a = new Complex(); // Declare, create and initialise an array of 3 // Complex values. // Complex[] b = { new Complex(), new Complex(), new Complex() ; // The instance variables of each Complex value // are accessible using the dot operator. Note that all // these fields have been initialised to 0.0 (doubles). // System.out.println("a.r == " + a.r + " a.i == " + a.i); for (int j = 0; j < b.length; j++) { b[j].r = j; b[j].i = j; a.r = b[0].r*b[1].r - b[0].i*b[1].i; a.i = b[0].r*b[1].i + b[0].i*b[1].r;
4 Methods: The essential way in which Java improves on C is by allowing Methods as well as data in classes (C only allows data in structs.) It would be convenient to allow the user to add two Complex values without having to write out the addition in component form. To do this we write an add method and include it in the class definition. Complex.java public class Complex { public double r, i; public Complex add(complex v) { Complex result = new Complex(); result.r = r + v.r; result.i = i + v.i; return result;
5 p u b l i c C o m p l e x a d d ( C o m p l e x v ) { C o m p l e x r e s u l t = n e w C o m p l e x ( ) ; r e s u l t. r = r + v. r ; r e s u l t. i = i + v. i ; r e t u r n r e s u l t ; The method returns a reference to a C o m p l e x object. The Signature of the method (name + number & types of arguments.) Createanew C o m p l e x object to hold the sum. This is the r instance var of the object which owns this method (the current object. ) The method is available to all parts of a Java program.
6 The method is now available for use with Complexobjects.ItmaybeusedinotherJava source files exactly like any other instance method: // Declare Complex variables a & b. // Complex a = new Complex(), b = new Complex(); a.r = 2.0; a.i = 2.0; // a=2+j2 b.r = 4.0; b.i = -3.0; // b=4 j3 Complex c = a.add(b); // c=a+b=6 j1 As many methods as desired may be added to the class definition. This, for example, is multiplication: public Complex mul(complex v) { Complex result = new Complex(); result.r = r * v.r - i * v.i; result.i = i * v.r + r * v.i; return result;
7 Signatures & Name Overloading: A method in Java is identified by its Signature, which is more than just its name. A Signature comprises both the method name and the number and types of arguments that the method accepts. The name of a method does not have to be unique, several methods can share the same name, as long as their signatures are distinct. This is known as Name Overloading. So Complex may have several different add methods. E.g., we may wish to have an add method which accepts a double as its argument instead of a Complex object. The signature of this method is: add(double). Notice that neither the return type of this method nor the names of its formal parameter(s) are part of its signature.
8 public Complex add(complex v) { Complex result = new Complex(); result.r = r + v.r; result.i = i + v.i; return result; public Complex add(double real) { Complex result = new Complex(); result.r = r + real; result.i = i; return result; Sometimes we refer to the signature of a method as its entire first line. public Complex add(double real) This is useful when we want to specify what a method should look like to the outside world, but the names of the arguments (formal parameters) are not really relevant, and the return type of the method isn t, strictly speaking, part of the signature.
9 If a class contains overloaded methods the Java compiler decides which one to call by looking at the types and number of parameters in a message. Complex a = new Complex(), b = new Complex(); a.r = 2.0; a.i = 2.0; // a=2+j2 b.r = 4.0; b.i = -3.0; // b=4 j3 // In this example call add(complex) because the // add message has a single Complex parameter. Complex c = a.add(b); // c=a+b=6 j1 // Whereas in this one call add(double) because // this add message has a single double parameter. Complex d = b.add(2.0); // d=6 j3 // In this case we also call add(double) because // this add message has a single float parameter, // which may be promoted (via an implicit cast) to // type double but not to type Complex. a = a.add(10.0f); // a=12+j2
10 Note that the complier attempts to get the closest match it can between signatures and message parameters. Hence, if we have a method with signature add(float), as well as one with signature add(double), Java will use the former as the method called by a message like a.add(10.0f), rather than the latter. The this reference: Used within an instance method, the keyword this is a reference to the Current Object (the object the method belongs to). It is used in three ways in instance methods: 1. In return statements where it is desired to return a reference to the current object. 2. To disambiguate references to the current object s instance variables where these have been hidden by a method s local variables or formal parameters. 3. From a Constructor, this is used to call a constructor with a different argument list.
11 Returning a reference to the current object: The add methods described so far create new Complex objects to hold the results of the addition. We may wish to write a version of add which modifies the current object instead ( addon ). It would be natural in these circumstancestowanttoreturnareferencetothecurrent object. This is the purpose of the return this idiom. public Complex addon(complex b) { r += b.r; // Modify the i += b.i; // Current Object. return this; // Two ways to achieve the same result. Add b to a, // modifying a in the process, and put a reference to // the result of the addition in c as well. c = a.addon(b); // Version 1, c = a = a.add(b); // Version 2, less efficient.
12 Disambiguating references to the current object s instance variables: What happens if a local variable or a formal parameter in a method shares a name with an instance variable of the class? public class Complex { public double r, i; public Complex add(double r) { Complex result = new Complex(); result.r = r + r; result.i = i; return result; All uses of r within the method refer to the most recently declared r, i.e., the formal parameter. The instance variable r ishidden or Aliased by the formal parameter. The same thing happens if r is a local variable.
13 How to get around this problem and access the instance variable? Use the this reference with the dot operator: public class Complex { public double r, i; public Complex add(double r) { Complex result = new Complex(); result.r = this.r + r; result.i = i; return result;. The use of this & the dot operator is always legal when accessing instance variables (e.g., result.i = i is actually shorthand for result.i = this.i ), but is only necessary when an ambiguity would otherwise occur.
14 Constructors: An Object Constructor is a special method which Java will call automatically when a new instance of the class containing that constructor is created. Constructors are used to help to build new objects. Java will first allocate memory for the object s variables and will then call the appropriate constructor to initialise these variables to desired values. A constructor looks like a method, but has a special name. The name of a constructor is always the same as the name of its class. A class can have as many constructors as its designer thinks fit. All the constructors of a class must have unique signatures. As all the constructors in a class share the same name, this means that they must have distinct argument lists.
15 public class Complex { public double r, i; // Constructor without arguments (default // constructor). Set both the real and imaginary // components of the Complex value to 0.0. public Complex() { r = i = 0.0; // Constructor taking 2 arguments, the real and // imaginary components of a Complex number. public Complex(double r, double i) { this.r = r; this.i = i; // Constructor taking a single argument, the real // part of a Complex number. The imaginary // component is set to zero. public Complex(double real) { r = real; i = 0.0;.
16 Note that the constructors have no return type, not even void. It is not possible to call a constructor explicitly, so there is no point in specifying what type a call should return. The sort of constructor that the system will invoke is determined by the argument list passed to the new statement when an object is created: Complex a, b, c; // Empty argument list to new Complex statement, // system will use default constructor, a=0+j0. a = new Complex(); // Two arguments to new Complex statement, // system will use 2-argument constructor, b=2+j2. b = new Complex(2.0, 2.0); // Single argument to new Complex statement, // system will use 1-arg constructor, c= 4+j0. c = new Complex(-4.0);
17 All but the most trivial classes should include a constructor. If a class does not have any constructors, the system will automatically create a default constructor for the class. This constructor will invoke the default constructor of the object s superclass. This used in Constructors: It may sometimes be useful to have one constructor call another. For example, we might observe that using the default constructor to create a Complex object is the same as using the 2-argument constructor with argument list (0, 0). Similarly, using the 1-argument constructor with value x is the same as using the 2- argument constructor with argument list (x, 0). Hence, both the default and the 1-argument constructor might achieve their ends by calling the 2-argument constructor. But directly calling a constructor is, in general, not possible.
18 Fortunately, the designers of Java have anticipated this problem, and provide a special syntax to allow one constructor to call another, using the this reference: public class Complex { public double r, i; // Constructor taking 2 arguments, the real and // imaginary components of a Complex number. public Complex(double r, double i) { this.r = r; this.i = i; // Default constructor. public Complex() { this(0.0, 0.0); // Single argument constructor. public Complex(double r) { this(r, 0.0); Useful when a lot of very similar processing is needed by a number of related constructors.
19 Formal & Actual Parameter Lists: The list of arguments in a method declaration is called the Formal Parameter List of the method. The list of arguments in a message to an object is called the Actual Parameter List of the method call. Formal parameter list of method. public Complex add(double real) { return new Complex(r + real, i); // Message to object a contains the actual parameter // list of the method call, in this case the double // value increment. c = a.add(increment); Actual parameter list of method call
20 When calling a method, Java first copies the values in the actual parameter list of the call into the slots in the formal parameter list of the method, then it executes the method s code. real: 24. increment: 24 slot for formal parameter of method add value stored in increment copied into real before add starts running. storage space for double variable increment memory This means that if a formal parameter of a method is a primitive type, changes made to the formal parameter within the method will not affect the value of the actual parameter passed to the method, because it is the copy which gets modified ( Pass by Value ).
21 But if the argument to a method is any sort of object, then it is the reference to that object that gets copied into the slot in the formal parameter list, not the object itself. Hence, any alteration made to the object in the method causes a global alteration to the state of the object. v: 0x b: 0x slot for formal parameter v of method add value stored in b copied into v before add starts running. storage space for reference variable b memory Storage space for object referenced by b and v is at memory location 0x Calling method add(complex v) with message a.add(b). The variable b and the formal parameter v are reference types. ( Pass by Reference ).
22 Methods and Arrays: Methods may be defined to return arrays as well as scalars: public double[] getrealandimag() { double[] elements = new double[2]; elements[0] = r; elements[1] = i; return elements; An equivalent definition is: public double getrealandimag()[] { double[] elements = { r, i ; return elements; Here the method getrealandimag creates and returns a 2-element double array which contains the real and imaginary components of the Complex object to which the method belongs. Note the two equivalent forms for declaring that the method returns an array. The former is preferred.
23 Because arrays are objects, hence pass by reference, we can also pass an array as a parameter to a method and have the method change its contents: public void getrealandimag( double[] elements) { elements[0] = r; elements[1] = i; Note that the array elements must exist before the method is called (and be big enough to hold the result). double[] elts = new double[2]; Complex c = new Complex(-2.0, 5.4); System.out.println("Before: c == " + elts[0] + ", " + elts[1]); c.getrealandimag(elts); System.out.println("After: c == " + elts[0] + ", " + elts[1]);
24 Viewing the value of an object, the tostring method: It is good practice for all classes to define a tostring instance method with the following signature : String tostring() When sent as a message to an object, to- String should return a String representation of the object s current value. Complex c(3.0, -4.8); String s = c.tostring(); System.out.println(s); What makes tostring interesting is that the Java language will automatically call it if it sees an attempt to concatenate a String object with a non-string. Java overloads the + operator to perform string concatenation when one of its elements is a String.
25 System.out.println("c == " + c); Concatenation of String "c == " with Complex object c.callc.tostring() to convert c. Here is an implementation of tostring for Complex. It builds the character representation of the object in a StringBuffer first, then converts this to a String, which it returns: public String tostring() { StringBuffer s = new StringBuffer(20); s.append(r); if ( i!= 0.0 ) { if ( i < 0.0 ) s.append(" -"); else s.append(" +"); s.append(" j"); s.append(math.abs(i)); return s.tostring(); Complex c prints as j4.8.
26 Data Abstraction & Information Hiding Onewaytouseclassesisasawayofimplementing Abstract Data Types (ADTs). The Complex type developed earlier is a sort of ADT, we have Complex objects and methods for manipulating these objects. However, it is not a pure ADT, because the user of a Complex object can directly manipulate the data it encapsulates (i.e., the instance variables of the type.) This is not regarded as the best way to design an Abstract Data Type because it commits us to a particular way of representing a Complex object internally, (in terms of its Cartesian components.) However, this is just one way of representing a Complex object, we might instead prefer to use polar components (magnitude and angle), for some purposes. The problem with our current implementation is that, once it has been released for use, we can no
27 longer make this change, we are committed to one particular form of internal representation. In a pure ADT the user is denied access to any internal implementation details (Information Hiding.) Instead, we present an Application Programming Interface (API) to the user. User Accesses ADT via API Application Programming ADT Kernel (private variables & methods) Interface (Public Methods) This interface acts as a buffer between the user of an ADT object and its internal implementation details. The user is only allowed to
28 manipulate an ADT object by calling methods defined in its API. Any other methods and data belonging to the object are hidden, and only accessible indirectly. (N.B., many of the Java library classes give you access to instance variables, but normally restrict you to read-only access, i.e., you are not allowed to assign to an instance variable. This is usually regarded as acceptable in ADT design.) Hence, the API of an abstract data type provides a Controlled and Documented way for the user of that ADT to employ ADT objects. The user is limited to using the ADT in predefined ways allowed by its designer: Restricted Access. Advantages of the API approach to ADT design: Decoupling of interface & implementation. Access control over ADT data.
29 Decoupling of Interface and Implementation: A well designed application programming interface is a Contract between the designer of an abstract data type and its users. The designer knows that the users of the type can only access it via its API. Hence, the designer is free to change the implementation of the ADT at any time, without affecting any userlevel software that employs that ADT. If the API is kept the same during revisions of the implementation, the user won t even know that anything has changed (except that the ADT might become faster, or more efficient), its logical behaviour will remain constant. The designer guarantees that the ADT will behave as advertised in its API, but reserves the right to implement the ADT in the most appropriate fashion. The interface and implementation have been Decoupled.
30 Access Control over ADT data: Consider an ADT which models a bank account. It contains an instance variable currentbalance. It would be highly inappropriate if the users of the bank account object had the freedom to access this instance variable directly. ash C w a r d h t i w current- Balance d e p o s i t C a s h Instead, the designer wraps an API around currentbalance so that its value can only be changed via well controlled methods: depositcash and withdrawcash. The former method only allows positive amounts of cash to
31 be deposited in the account, and the latter only allows withdrawals of positive amounts of cash less than or equal to currentbalance. Here we have implemented an Access Control system on the ADT. The user can only get at the instance variable currentbalance through methods which restrict the sorts of operations that are legal on this variable. The private keyword, protecting class data: public class Complex { private double r, i;. By declaring a variable private inaclass, we are saying that the only methods which are allowed to access (read or write) the variable
32 are methods belonging to this class. Asfaras all other methods in the program are concerned, the variable is invisible. Accessor and Mutator methods, accessing class data: public class BankBalance { private double currentbalance; public BankBalance() { currentbalance = 0.0; // Accessor method, find current balance in acc. public double getbalance() { return currentbalance; // Mutator method, deposit an amount, c, of cash. public void depositcash(double c) { if ( c > 0.0 ) currentbalance += c;.
33 public class Complex { private double r, i; public Complex() { r = i = 0.0; public Complex(double r, double i) { this.r = r; this.i = i; // Accessor methods. public double getreal() { return r; public double getimag() { return i; public double getmag() { return Math.sqrt(r*r + i*i); // See the java.lang.math documentation for // information on atan2. public double getangle() { return Math.atan2(i, r);
34 // Mutator methods. public Complex setrealandimag( double r, double i) { this.r = r; this.i = i; return this; public Complex setmagandangle( double m, double a) { this.r = m * Math.cos(a); this.i = m * Math.sin(a); return this;. // Rest of class definition here.. // End class Complex. In this version of classcomplex the user cannot tell (without reading the source code) what sort of internal representation is being used, Cartesian or polar. If the class designer were to decide to change the internal representation of this class, the user wouldn t notice the change. In fact, programs written to use this class would not even need to be recompiled.
35 Developing Classes This is a four-step process: 1. Define the problem (problem statement). 2. Define the API for the ADT. 3. Decide on an appropriate internal data representation. 4. Implement the methods. As an example we will present the design of a Matrix class. Define the problem: Thefirstthingtodoistodecideclearlywhatit is that the ADT models. This should be written out as a succinct statement: Design a Matrix ADT which implements simple matrix arithmetic, viz., addition, subtraction and multiplication of matrices. All indices should be 1 rather than 0-based.
36 Define the API: The API is the view that the user will have of the new ADT. It is important to try to get everything needed in here. Note that this definition is made before we know how the ADT will be implemented: Methods: Matrix add(matrix b) Add a matrix, b, to the current matrix, cm, assuming they are the same size. The result will be returned in a new matrix, neither cm nor b being changed. If cm and b are not the same size, generate an error message and halt. Matrix sub(matrix b) Similar to add, except that b is subtracted from cm. Matrix mul(matrix b) Multiply cm by b, returning the result in a new matrix. Cm and b remain unchanged. If cm and b do not conform (i.e., if the number of columns in cm is not the same as the number of rows in b), generate an error message and halt.
37 Constructor: Matrix(int r, int c) Make a new Matrix object with r rows and c columns. The elements of the Matrix will all be doubles, and will be initialised to zeroes. If either r or c is negative or zero, generate an error message and halt. Accessor & Mutator methods: int getrows() Return the number of rows in the current Matrix. int getcols() Return the number of columns in the current Matrix. double getelt(int r, int c) Return the value of location (r, c) in the current Matrix. If either r or c is outside the bounds of the current Matrix, generate an error message and halt. Note that indices in the Matrix are 1-based, so that the first element is at location (1, 1), not (0, 0). Matrix setelt(int r, int c, double val) Set location (r, c) in the current Matrix to value val. If either r or c is outside the bounds of the current Matrix, generate an error message and halt. Note that indices in the Matrix are 1-based, as in getelt. This method returns a reference to the modified Matrix.
38 Utility method: String tostring() Generate a printable representation of the current Matrix object and return it. The current object is not modified by this method. Decide on an internal data representation: We decide to use a 2-d array of double values, with rows columns elements in it. Each Matrix object will also have to keep track of how big it is: public class Matrix { private double[][] elts; private int rows, columns; Implement the methods: The add and sub methods are very similar. In particular, they both need to check that the matrices being added are of the same size.
39 public Matrix add(matrix b) { checksize(b); Matrix res = new Matrix(rows, columns); for (int r = 0; r < rows; r++) for (int c = 0; c < columns; c++) res.elts[r][c] = elts[r][c] + b.elts[r][c]; return res; public Matrix sub(matrix b) { checksize(b); Matrix res = new Matrix(rows, columns); for (int r = 0; r < rows; r++) for (int c = 0; c < columns; c++) res.elts[r][c] = elts[r][c] - b.elts[r][c]; return res; Both of these methods need a way to check that the current matrix and the argument to the method have the same number of rows and columns. This job has been abstracted into method checksize. But checksize is an operation
40 which is private to the class, a user of the class should not be able to call it directly. We can make checksize inaccessible to outside users by declaring it with the private keyword: private void checksize(matrix b) { if ( rows!= b.rows columns!= b.columns ) fatalerror("add/sub: mismatch"); This is now a method which can only be accessed from within Matrix. It provides a service to the publicly accessible methods of the class. fatalerror is another example of a private utility method. If called, it prints a message to the error stream and stops the program. private void fatalerror(string s) { System.err.println( "Matrix: fatal error: " + s); System.exit(0);
41 The method mul performs the multiplication operation between matrices. This method has little commonality with others, in particular, its test to see if the two matrices can be multiplied (i.e., that they conform ), is unlike the size checks for addition and subtraction. Instead, the method must check to see if the number of columns in the multiplicand (the current object) is the same as the number of rows in the multiplier (the argument to the method.) public Matrix mul(matrix b) { if ( columns!= b.rows ) fatalerror("nonconforming matrices"); Matrix res = new Matrix(rows, b.columns); for (int r = 0; r < res.rows; r++) { for (int c = 0; c < res.columns; c++) { double acc = 0.0; for (int i = 0; i < columns; i++) acc += elts[r][i] * b.elts[i][c]; res.elts[r][c] = acc; return res;
42 The accessor methods getrows and get- Cols are straightforward. Their only purpose is to protect the inner workings of the class from modification by the user (which would be possible if the instance variables rows and columns weremadepublic.) public int getrows() { return rows; public int getcols() { return columns; (There is a way to allow read-only access to the instance variables rows and columns, but we won t use it here.) The accessor methods getelt and setelt are quite similar to one another. Both need to check that their indices are within bounds, and both need to convert the 1-based Matrix indices which are passed as parameters to them, to 0-based indices suitable for accessing the
43 elts array where the elements of the Matrix are stored. public double getelt(int r, int c) { r = checkrowindex(r); c = checkcolumnindex(c); return elts[r][c]; public Matrix setelt(int r, int c, double val) { r = checkrowindex(r); c = checkcolumnindex(c); elts[r][c] = val; return this; The utility methods are checkrowindex and checkrowindex. As well as checking that their indices are within the appropriate ranges, these methods perform the 1-based to 0-based index conversion. Here is checkrowindex : private int checkrowindex(int r) { if ( r < 1 r > rows ) fatalerror("row index " + r + " out of range"); return r - 1;
44 Finally there is the tostring method, whose job it is to generate a printable representation of a Matrix. We choose to print a Matrix in the following, single-line, form: [[2.0, -4.2], [0.0, 1.0], [0.7, 4.5]] (Thisisa3x2Matrix.)Hereisthecode: public String tostring() { StringBuffer buf = new StringBuffer(80); for (int r = 0; r < rows; r++ ) { buf.append((r == 0? "[" : ", ")); for (int c = 0; c < columns; c++) { buf.append((c == 0? "[" : ", ")); buf.append(elts[r][c]); buf.append("]"); buf.append("]"); return buf.tostring(); As with the tostring method from class Complex, weuseastringbuffer to accumulate the result, because it can grow in size as needed, and later turn it into a String.80 is an initial guess at how big the buffer should be.
45 Here is the whole class definition for Matrix: Matrix.java public class Matrix { // Instance variables. Data elements are // stored in a 2-d array with rows x columns // elements. private double[][] elts; private int rows, columns; // Constructor. This class has no default // constructor. public Matrix(int r, int c) { rows = r; columns = c; if ( rows > 0 && columns > 0 ) elts = new double[rows][columns]; else fatalerror("constructor " + r + ", " + c); // Accessor methods. // Accessor method, get the number of rows in the // Matrix. public int getrows() { return rows; // Accessor method, get the number of columns in // the Matrix. public int getcols() { return columns;
46 Matrix.java continued: // Accessor method, get an element of the Matrix. public double getelt(int r, int c) { r = checkrowindex(r); c = checkcolumnindex(c); return elts[r][c]; // Mutator method, set an element of the Matrix. public Matrix setelt(int r, int c, double val) { r = checkrowindex(r); c = checkcolumnindex(c); elts[r][c] = val; return this; // add method. Add a Matrix passed as an argument // to the current Matrix object and return a new // result Matrix. public Matrix add(matrix b) { checksize(b); Matrix res = new Matrix(rows, columns); for (int r = 0; r < rows; r++) for (int c = 0; c < columns; c++) res.elts[r][c] = elts[r][c] + b.elts[r][c]; return res; // sub method. Very similar in structure to add, // but performs subtraction. public Matrix sub(matrix b) { checksize(b); Matrix res = new Matrix(rows, columns); for (int r = 0; r < rows; r++) for (int c = 0; c < columns; c++) res.elts[r][c] = elts[r][c] - b.elts[r][c]; return res;
47 Matrix.java continued: // mul method. Multiply the current Matrix object by // a Matrix passed as an argument to the method and // return a new result Matrix. public Matrix mul(matrix b) { if ( columns!= b.rows ) fatalerror("matrices do not conform"); Matrix res = new Matrix(rows, b.columns); for (int r = 0; r < res.rows; r++) { for (int c = 0; c < res.columns; c++) { double acc = 0.0; for (int i = 0; i < columns; i++) acc += elts[r][i] * b.elts[i][c]; res.elts[r][c] = acc; return res; // tostring method. Generate a String object which // represents the current Matrix object. public String tostring() { StringBuffer buf = new StringBuffer(80); for (int r = 0; r < rows; r++ ) { buf.append((r==0? "[" : ", ")); for (int c = 0; c < columns; c++) { buf.append((c==0? "[" : ", ")); buf.append(elts[r][c]); buf.append("]"); buf.append("]"); return buf.tostring();
48 Matrix.java continued: // Private methods, unique to this class. // fatalerror prints an error message (which it // receives as an argument) to the standard error // stream, then halts the program. This is not an // ideal way to handle errors, it would be better // to use Java s exception mechanism. private void fatalerror(string errormessage) { System.err.println("Matrix: fatal error: " + errormessage); System.exit(0); // checksize checks to see if its argument (a Matrix) // has the same number of rows and columns as the // current Matrix object. Needed for addition and // subtraction. private void checksize(matrix b) { if ( rows!= b.rows columns!= b.columns ) fatalerror("add/sub: size mismatch"); // checkrowindex checks that its argument is a valid // row index (i.e., 1 <= r <= rows), then performs // 1- to 0-based index conversion and returns a // 0-based index. private int checkrowindex(int r) { if ( r < 1 r > rows ) fatalerror("row index " + r + " out of range"); return r - 1;
49 Matrix.java continued: // checkcolumnindex checks that its argument is a // valid column index (i.e., 1 <= c <= columns), // then performs 1- to 0-based index conversion and // returns a 0-based index. private int checkcolumnindex(int c) { if ( c < 1 c > columns ) fatalerror("column index " + c + " out of range"); return c - 1; // main method, useful for testing, use "java // Matrix" to invoke this method and run the suite // of tests. Every ADT should include a main method // like this which provides a testbench exercising // the capabilities of the ADT. public static void main(string[] args) { int r, c; Matrix a = new Matrix(4, 3); Matrix b = new Matrix(4, 3); System.out.println("a = " + a); System.out.println("a has " + a.getrows() + " rows and " + a.getcols() + " columns."); System.out.println("b = " + b); System.out.println("b has " + b.getrows() + " rows and " + b.getcols() + " columns."); for (r = 1; r <= a.getrows(); r++) for (c = 1; c <= a.getcols(); c++) { a.setelt(r, c, (double)(r * c)); b.setelt(r, c, (double)(r + c));
50 Matrix.java continued: // main method contined from previous page. System.out.println("a is now: " + a); System.out.println("b is now: " + b); System.out.println("Accessing elements of a & b"); for (r = 1; r <= a.getrows(); r++) for (c = 1; c <= a.getcols(); c++) { System.out.print("a(" + r + ", " + c + ") = " + a.getelt(r, c) + " "); System.out.println("b(" + r + ", " + c + ") = " + b.getelt(r, c)); System.out.println("a + b = " + a.add(b)); System.out.println("a - b = " + a.sub(b)); Matrix x = new Matrix(3, 4); for (r = 1; r <= x.getrows(); r++) for (c = 1; c <= x.getcols(); c++) x.setelt(r, c, (double)(r * c)); System.out.println("a = " + a); System.out.println("x = " + x); System.out.println("a * x = " + a.mul(x)); System.out.println("x * a = " + x.mul(a)); // end of method main (test suite) // end of class Matrix Totest theadt, use java Matrix. This will call the main method associated with the class. Including a main method with an ADT for testing is quite a common practice in OOP.
Chapter 4 Defining Classes I
Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the
More informationAP Computer Science Chapter 10 Implementing and Using Classes Study Guide
AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationCOMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation
COMP-202 Unit 8: Defining Your Own Classes CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation Defining Our Own Classes (1) So far, we have been creating
More informationDefining Classes and Methods
Defining Classes and Methods Chapter 4 Chapter 4 1 Basic Terminology Objects can represent almost anything. A class defines a kind of object. It specifies the kinds of data an object of the class can have.
More informationB16 Object Oriented Programming
B16 Object Oriented Programming Michael A Osborne mosb@robots.ox.ac.uk http://www.robots.ox.ac.uk/~mosb/b16.html Hilary 2014 Topic 4: Constructors Recall our definition of the Complex class. class Complex
More informationCS112 Lecture: Defining Instantiable Classes
CS112 Lecture: Defining Instantiable Classes Last revised 2/3/05 Objectives: 1. To describe the process of defining an instantiable class 2. To discuss public and private visibility modifiers. Materials:
More informationתרגול 9 מחלקות ואובייקטים
תרגול 9 מחלקות ואובייקטים 1 1. Complex Numbers Design class Complex, representing an immutable complex number. Use this class to read two complex numbers from the user, print their sum and product, and
More informationB16 Object Oriented Programming
B16 Object Oriented Programming Michael A. Osborne mosb@robots.ox.ac.uk http://www.robots.ox.ac.uk/~mosb/teaching.html#b16 Hilary 2013 Topic 4: Constructors Recall our definition of the Complex class.
More informationAnatomy of a Class Encapsulation Anatomy of a Method
Writing Classes Writing Classes We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4 focuses on: class definitions instance data encapsulation and
More informationSTUDENT LESSON A5 Designing and Using Classes
STUDENT LESSON A5 Designing and Using Classes 1 STUDENT LESSON A5 Designing and Using Classes INTRODUCTION: This lesson discusses how to design your own classes. This can be the most challenging part of
More informationSoftware Design and Analysis for Engineers
Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:
More informationGraphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java
More information3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.
3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.
More informationCHAPTER 7 OBJECTS AND CLASSES
CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and
More informationCOMP 250 Winter 2011 Reading: Java background January 5, 2011
Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP
More informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationChapter 4. Defining Classes I
Chapter 4 Defining Classes I Introduction Classes are the most important language feature that make object oriented programming (OOP) possible Programming in Java consists of dfii defining a number of
More informationIn Java there are three types of data values:
In Java there are three types of data values: primitive data values (int, double, boolean, etc.) arrays (actually a special type of object) objects An object might represent a string of characters, a planet,
More informationCOP 3330 Final Exam Review
COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time
More informationObject Oriented Programming
Object Oriented Programming Objectives To review the concepts and terminology of object-oriented programming To discuss some features of objectoriented design 1-2 Review: Objects In Java and other Object-Oriented
More informationImperative Languages!
Imperative Languages! Java is an imperative object-oriented language. What is the difference in the organisation of a program in a procedural and an objectoriented language? 30 class BankAccount { private
More informationArrays, Vectors, Matrices
Arrays, Vectors, Matrices Goal: o Scientific Eng. o Numerical computations o Array are very efficient way of organizing data since accessing array elements requires O(1). Characteristics of an array: o
More informationcoe318 Lab 2 ComplexNumber objects
Objectives Overview coe318 Lab 2 objects Implement a class. Learn how immutable objects work. Week of September 15, 2014 Create a project with more than one class. Duration: one week. In mathematics, complex
More informationObject-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007
Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007 Java We will be programming in Java in this course. Partly because it is a reasonable language, and partly because you
More informationWhat are the characteristics of Object Oriented programming language?
What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is
More informationCHAPTER 7 OBJECTS AND CLASSES
CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and
More informationClass 15. Object-Oriented Development from Structs to Classes. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)
Class 15 Object-Oriented Development from Structs to Classes The difference between structs and classes A class in C++ is basically the same thing as a struct The following are exactly equivalent struct
More informationKapil Sehgal PGT Computer. Science Ankleshwar Gujarat
Classes Chapter 4 Classes and Objects Data Hiding and Encapsulation Function in a Class Using Objects Static Class members Classes Class represents a group of Similar objects A class is a way to bind the
More informationD Programming Language
Group 14 Muazam Ali Anil Ozdemir D Programming Language Introduction and Why D? It doesn t come with a religion this is written somewhere along the overview of D programming language. If you actually take
More informationUNDERSTANDING CLASS DEFINITIONS CITS1001
UNDERSTANDING CLASS DEFINITIONS CITS1001 Main concepts to be covered Fields / Attributes Constructors Methods Parameters Source ppts: Objects First with Java - A Practical Introduction using BlueJ, David
More informationHST 952. Computing for Biomedical Scientists Lecture 5
Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952 Computing for Biomedical Scientists Lecture 5 Outline Recursion and iteration Imperative and
More informationComputer Science II (20073) Week 1: Review and Inheritance
Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system
More informationCOMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others
COMP-202 Objects, Part III Lecture Outline Static Member Variables Parameter Passing Scopes Encapsulation Overloaded Methods Foundations of Object-Orientation 2 Static Member Variables So far, member variables
More informationJAVA: A Primer. By: Amrita Rajagopal
JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently
More informationMore About Objects. Zheng-Liang Lu Java Programming 255 / 282
More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism
More informationCS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class
CS112 Lecture: Defining Classes Last revised 2/3/06 Objectives: 1. To describe the process of defining an instantiable class Materials: 1. BlueJ SavingsAccount example project 2. Handout of code for SavingsAccount
More informationZheng-Liang Lu Java Programming 45 / 79
1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 45 / 79 Example Given a radius
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationDefensive Programming
Defensive Programming Software Engineering CITS1220 Based on the Java1200 Lecture notes by Gordon Royle Lecture Outline Why program defensively? Encapsulation Access Restrictions Documentation Unchecked
More informationOOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.
OOPs Concepts 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. Type Casting Let us discuss them in detail: 1. Data Hiding: Every
More informationTable 2 1. F90/95 Data Types and Pointer Attributes. Data Option. (Default Precision) Selected-Int-Kind
Chapter 2 Data Types Any computer program is going to have to operate on the available data. The valid data types that are available will vary from one language to another. Here we will examine the intrinsic
More informationObjects and Classes -- Introduction
Objects and Classes -- Introduction Now that some low-level programming concepts have been established, we can examine objects in more detail Chapter 4 focuses on: the concept of objects the use of classes
More informationpublic class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods
Main concepts to be covered Understanding class definitions Looking inside classes fields constructors methods parameters assignment statements 5.0 2 Ticket machines an external view Exploring the behavior
More information1 Shyam sir JAVA Notes
1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write
More informationDay 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University
Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays
More informationUtilities (Part 2) Implementing static features
Utilities (Part 2) Implementing static features 1 Goals for Today learn about preventing class instantiation learn about methods static methods method header method signature method return type method
More informationCOMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading
COMP 202 CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading More on OO COMP 202 Objects 3 1 Static member variables So far: Member variables
More informationis the and x A. The transpose of A, denoted
CMPS 101 lgorims and bstract Data ypes Programming ssignment 3 In is assignment you will create a calculator for performing matrix operations at exploits e (expected) sparseness of it s matrix operands.
More informationCS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms
CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()
More information1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!
//Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new
More informationFall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.
Grading Page 1 / 4 Page3 / 20 Page 4 / 13 Page 5 / 10 Page 6 / 26 Page 7 / 17 Page 8 / 10 Total / 100 1. (4 points) What is your course section? CS 101 CS 101E Pledged Page 1 of 8 Pledged The following
More informationObject Oriented Programming in C#
Introduction to Object Oriented Programming in C# Class and Object 1 You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create
More informationSTUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING
OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming
More informationJava and OOP. Part 2 Classes and objects
Java and OOP Part 2 Classes and objects 1 Objects OOP programs make and use objects An object has data members (fields) An object has methods The program can tell an object to execute some of its methods
More informationContainer Vs. Definition Classes. Container Class
Overview Abstraction Defining new classes Instance variables Constructors Defining methods and passing parameters Method/constructor overloading Encapsulation Visibility modifiers Static members 14 November
More informationLanguage Features. 1. The primitive types int, double, and boolean are part of the AP
Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are
More informationUnit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW
Prepared by: Dr. Abdallah Mohamed, AOU-KW 1 1. Introduction 2. Objects and classes 3. Information hiding 4. Constructors 5. Some examples of Java classes 6. Inheritance revisited 7. The class hierarchy
More informationG52CPP C++ Programming Lecture 7. Dr Jason Atkin
G52CPP C++ Programming Lecture 7 Dr Jason Atkin 1 This lecture classes (and C++ structs) Member functions inline functions 2 Last lecture: predict the sizes 3 #pragma pack(1) #include struct A
More informationLecture 12: Classes II
Lecture 12: Classes II Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. Encapsulation Encapsulation encapsulation: Hiding
More informationCOMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading
COMP 202 CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading More on OO COMP 202 - Week 7 1 Static member variables So far: Member variables
More information1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides
1B1b Inheritance Agenda Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented oriented programming. 1 2 Inheritance Models the kind-of or specialisation-of
More informationA A B U n i v e r s i t y
A A B U n i v e r s i t y Faculty of Computer Sciences O b j e c t O r i e n t e d P r o g r a m m i n g Week 4: Introduction to Classes and Objects Asst. Prof. Dr. M entor Hamiti mentor.hamiti@universitetiaab.com
More informationData Structures (list, dictionary, tuples, sets, strings)
Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access
More informationCpt S 122 Data Structures. Introduction to C++ Part II
Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function
More informationDOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS
Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully
More informationCLASSES AND OBJECTS IN JAVA
Lesson 8 CLASSES AND OBJECTS IN JAVA (1) Which of the following defines attributes and methods? (a) Class (b) Object (c) Function (d) Variable (2) Which of the following keyword is used to declare Class
More informationCSCI 355 LAB #2 Spring 2004
CSCI 355 LAB #2 Spring 2004 More Java Objectives: 1. To explore several Unix commands for displaying information about processes. 2. To explore some differences between Java and C++. 3. To write Java applications
More informationObject Oriented Methods : Deeper Look Lecture Three
University of Babylon Collage of Computer Assistant Lecturer : Wadhah R. Baiee Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces,
More informationCS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find
CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS
More informationFrom Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009
From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3 Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009 C++ Values, References, and Pointers 1 C++ Values, References, and Pointers 2
More informationInheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.
Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods
More informationG52CPP C++ Programming Lecture 9
G52CPP C++ Programming Lecture 9 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture const Constants, including pointers The C pre-processor And macros Compiling and linking And
More informationMethods and Data (Savitch, Chapter 5)
Methods and Data (Savitch, Chapter 5) TOPICS Invoking Methods Return Values Local Variables Method Parameters Public versus Private 2 public class Temperature { public static void main(string[] args) {
More informationCSCI 355 Lab #2 Spring 2007
CSCI 355 Lab #2 Spring 2007 More Java Objectives: 1. To explore several Unix commands for displaying information about processes. 2. To explore some differences between Java and C++. 3. To write Java applications
More informationC# Programming for Developers Course Labs Contents
C# Programming for Developers Course Labs Contents C# Programming for Developers...1 Course Labs Contents...1 Introduction to C#...3 Aims...3 Your First C# Program...3 C# The Basics...5 The Aims...5 Declaring
More informationTyped Racket: Racket with Static Types
Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type
More informationPart 3. Why do we need both of them? The object-oriented programming paradigm (OOP) Two kinds of object. Important Special Kinds of Member Function
Part 3 The object-oriented programming paradigm (OOP) Two kinds of object Value objects The object contains the member data items Allocated automatically just like primitive (built-in) data items Suitable
More informationCS61B Lecture #5: Arrays and Objects
CS61B Lecture #5: Arrays and Objects For faster response, please send urgent problems (like the lab files don t compile ) as mail to cs61b, rather than using class messages. Homeworks are generally due
More informationMore on Classes. 1 tostring
More on Classes 1 tostring Java allows us to supply an object wherever a string is expected. The run-time system will automatically apply a conversion function to create a string representation of the
More informationSri Vidya College of Engineering & Technology
UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the
More informationOperators and Expressions
Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions
More informationObject Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia
Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing
More informationLesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014
Lesson 10B Class Design By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Encapsulation Inheritance and Composition is a vs has a Polymorphism Information Hiding Public
More informationSchool of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15
Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL
More informationChapter 3: Operators, Expressions and Type Conversion
101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To
More informationLesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014
Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class
More informationObject Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year
Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures
More informationExercises Software Development I. 05 Conversions and Promotions; Lifetime, Scope, Shadowing. November 5th, 2014
Exercises Software Development I 05 Conversions and Promotions; Lifetime, Scope, Shadowing November 5th, 2014 Software Development I Winter term 2014/2015 Priv.-Doz. Dipl.-Ing. Dr. Andreas Riener Institute
More informationCS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes
CS111: PROGRAMMING LANGUAGE II Lecture 1: Introduction to classes Lecture Contents 2 What is a class? Encapsulation Class basics: Data Methods Objects Defining and using a class In Java 3 Java is an object-oriented
More informationCS112 Lecture: Working with Numbers
CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations
More informationJava Primer 1: Types, Classes and Operators
Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationCS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/
CS61C Machine Structures Lecture 4 C Pointers and Arrays 1/25/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Pointers (1) Common C Error There is a difference
More informationLecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University
Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types
More informationPointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory
Pointers A pointer is simply a reference to a variable/object Compilers automatically generate code to store/retrieve variables from memory It is automatically generating internal pointers We don t have
More informationExample: Count of Points
Example: Count of Points 1 public class Point { 2... 3 private static int numofpoints = 0; 4 5 public Point() { 6 numofpoints++; 7 } 8 9 public Point(int x, int y) { 10 this(); // calling Line 5 11 this.x
More informationVALLIAMMAI ENGINEERING COLLEGE
VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 603 203 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E. - Electrical and Electronics Engineering IV SEMESTER CS6456 - OBJECT ORIENTED
More informationCS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE
CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate
More informationFirst IS-A Relationship: Inheritance
First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class
More information