1 Classes Instructor: Mainak Chaudhuri

Slides:



Advertisements
Similar presentations
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Advertisements

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Inheritance Inheritance Reserved word protected Reserved word super
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
ASP.NET Programming with C# and SQL Server First Edition
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Object Oriented Software Development
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Object Oriented Programming Concepts OOP – reasoning about a program as a set of objects rather than as a set of actions Object – a programming entity.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Question of the Day  On a game show you’re given the choice of three doors: Behind one door is a car; behind the others, goats. After you pick a door,
Week 6 - Wednesday.  What did we talk about last time?  Exam 1!  And before that…  Review!  And before that…  Arrays and strings.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
1 Operators and Expressions Instructor: Mainak Chaudhuri
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programming in Java CSCI-2220 Object Oriented Programming.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Session 7 Methods Strings Constructors this Inheritance.
Classes One class usually represents one type of object –May contain its own member variables –May contain its own methods to operate on the member variables.
Outline Creating Subclasses Overriding Methods Class Hierarchies Visibility Designing for Inheritance Inheritance and GUIs The Timer Class Copyright ©
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Coming up: Inheritance
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
Interfaces and Inner Classes
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
College Board Topics – A.P. Computer Science A Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.
OOP Basics Classes & Methods (c) IDMS/SQL News
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
© 2004 Pearson Addison-Wesley. All rights reserved November 12, 2007 Inheritance ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
© 2004 Pearson Addison-Wesley. All rights reserved April 10, 2006 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING.
© 2004 Pearson Addison-Wesley. All rights reserved November 14, 2007 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL.
Class Definitions: The Fundamentals Chapter 6 3/30/15 & 4/2/15 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Methods, classes, and Objects Dr. Jim Burns. Question  Which of the following access modifiers is the default modifier?  public  private  protected.
1 More About Derived Classes and Inheritance Chapter 9.
Object-Oriented Concepts
Lecture 12 Inheritance.
Review What is an object? What is a class?
Writing Classes We have talked about classes and objects.
Chapter 3: Using Methods, Classes, and Objects
ATS Application Programming: Java Programming
Classes & Objects: Examples
Dr. Bhargavi Dept of CS CHRIST
Session 2: Introduction to Object Oriented Programming
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Presentation transcript:

1 Classes Instructor: Mainak Chaudhuri

2 Classes One class usually represents one type of object –May contain its own member variables –May contain its own methods to operate on the member variables Usually one class is defined in one Java file In the entire program exactly one class should contain a main method

3 Example: Vehicle Consider defining a class named Vehicle –It has certain number of wheels –It has certain number of windows –It has certain number of seats –It has a speed public class Vehicle { // objects of public classes can be accessed // from anywhere (more acceptable and useful) public int wheels; public int windows; public int seats; public double speed; }

4 Example: Vehicle We have defined the class Vehicle Now we need to use it class VehicleExample { // This class need not be public as the sole purpose of // this is to define the main method public static void main (String arg[]) { // Allocate an object of type Vehicle // Invoke default constructor Vehicle bicycle = new Vehicle(); Vehicle car = new Vehicle(); bicycle.wheels = 2; bicycle.windows = 0; bicycle.seats = 1; bicycle.speed = 5.0;// m/s // continued in next slide

5 Example: Vehicle car.wheels = 4; car.windows = 5; car.seats = 5; car.speed = 20.0; } Observations –Need a way to cleanly initialize the members –Need methods to do something interesting with the members

6 Example: Vehicle User-defined constructors public class Vehicle { public int wheels; public int windows; public int seats; public double speed; public Vehicle (int wh, int wi, int se, double sp) { wheels = wh; windows = wi; seats = se; speed = sp; } } // continued in the next slide

7 Example: Vehicle class VehicleExample { public static void main (String arg[]) { // Allocate an object of type Vehicle // Invoke constructor Vehicle bicycle = new Vehicle (2, 0, 1, 5.0); Vehicle car = new Vehicle (4, 5, 5, 20.0); }

8 Constructors Used to initialize the member variables Default constructor initializes these to zero Constructors are special type of methods –Do not have a return type (not even void) –Must be public so that they can be accessed from a different class –Cannot be static: static methods can be invoked without attaching them to any object e.g., main; constructors by definition must be invoked for a particular object

9 Example: Vehicle Let us add one more method in the Vehicle class public class Vehicle { public int wheels; public int windows; public int seats; public double speed; public Vehicle (int wh, int wi, int se, double sp) { wheels = wh; windows = wi; seats = se; speed = sp; } // continued in the next slide

10 Example: Vehicle public void print () { System.out.println (“Wheels: ” + wheels); System.out.println (“Windows: ” + windows); System.out.println (“Seats: ” + seats); System.out.println (“Speed: ” + speed); } } // end class

11 Example: Vehicle class VehicleExample { public static void main (String arg[]) { Vehicle bicycle = new Vehicle (2, 0, 1, 5.0); Vehicle car = new Vehicle (4, 5, 5, 20.0); System.out.println (“Bicycle:”); bicycle.print(); System.out.println(“Car:”); car.print(); }

12 Example: Vehicle Let us give a name to the vehicle public class Vehicle { public int wheels; public int windows; public int seats; public double speed; public String name; public Vehicle (int wh, int wi, int se, double sp, String s) { wheels = wh; windows = wi; seats = se; speed = sp; name = new String (s); } // continued in the next slide

13 Example: Vehicle public void print () { System.out.println (name); System.out.println (“Wheels: ” + wheels); System.out.println (“Windows: ” + windows); System.out.println (“Seats: ” + seats); System.out.println (“Speed: ” + speed); } } // end class // continued in the next slide

14 Example: Vehicle class VehicleExample { public static void main (String arg[]) { Vehicle bicycle = new Vehicle (2, 0, 1, 5.0, “Bicycle”); Vehicle car = new Vehicle (4, 5, 5, 20.0, “Car”); bicycle.print(); car.print(); }

15 Information hiding Why classes? –Idea is to encapsulate the “properties” of a class of objects into a compact structure –Not to allow direct access to members of a class unless there is a good reason –Allow access to members only through member methods: often called interfaces –One object can talk to another only if there is a proper “channel” to do so: defines a natural hierarchy Upshot –Most member variables are private –Need methods to read/write from/to the variables

16 Information hiding Consider a calculator –Customer is often not concerned with the internal architecture –Nor concerned about the algorithms implemented for addition, multiplication, etc. –As long as a calculator offers interfaces to do addition, subtraction, etc., the customer is happy –A calculator properly implemented as a class would allow you to hide these information –Often such a class is said to define an abstract data type

17 Designing an OO project Some general and probably obvious guidelines –Decide the components of your project –These will become the objects Decide if you need to further split the objects into finer objects (each object should be simple) –Decide the constituents of each object These will become the member variables –Lay out the components on paper with relationships among them clearly shown –The connections between the objects become the supported public methods –Decide the private methods to fully implement the objects

18 Example: polynomial A polynomial is an aggregate of algebraic terms Each term has a coefficient and an array of indices, one for each variable Need three classes: an AlgebraicTerm class, a polynomial class, and a top level class implementing main

19 Example: polynomial public class AlgebraicTerm { private double coefficient; private int[] index; // General constructor public AlgebraicTerm (double coefficient, int[] index) { int numVar = index.length; int i; this.index = new int[numVar]; for (i=0; i<numVar; i++) { this.index[i] = index[i]; } this.coefficient = coefficient; } // continued in next slide

20 Example: polynomial // Special constructor for univariate // Note: method overloading public AlgebraicTerm (double coefficient, int index) { this.coefficient = coefficient; this.index = new int[1]; this.index[0] = index; } // continued in next slide

21 Example: polynomial public double Evaluate (double[] v) { int i; double value = coefficient; for (i=0; i<index.length; i++) { // Could say this.index[i] // But not needed value *= Math.pow(v[i], index[i]); } return value; } // continued in next slide

22 Example: polynomial public AlgebraicTerm Add (AlgebraicTerm aterm) { AlgebraicTerm rterm = null; if (checkConsistency (aterm)) { rterm = new AlgebraicTerm (coefficient+aterm.GetCoefficient(), index); } return rterm; } // continued in next slide

23 Example: polynomial public double GetCoefficient () { return coefficient; } public int[] GetIndex () { return index; } // continued in next slide

24 Example: polynomial private boolean checkConsistency (AlgebraicTerm aterm) { return (index.length == aterm.GetIndex().length); } } // end of AlgebraicTerm class; could // make it richer

25 Example: polynomial public class Polynomial { AlgebraicTerm [] terms; public Polynomial (double [] coefficient, int [] index[], int numVar) { int nTerms = coefficient.length; int i; terms = new AlgebraicTerm[nTerms]; for (i=0; i<nTerms; i++) { terms[i] = new AlgebraicTerm (coefficient[i], index[i]); } } // continued in next slide

26 Example: polynomial public Polynomial (AlgebraicTerm [] t) { int nTerms = t.length; int i; terms = new AlgebraicTerm[nTerms]; for (i=0; i<nTerms; i++) { terms[i] = t[i]; // use carefully } // continued in next slide

27 Example: polynomial public void SetTerms (AlgebraicTerm[] terms) { this.terms = terms; } public AlgebraicTerm[] GetTerms () { return terms; } // continued in next slide

28 Example: polynomial public double Evaluate (double[] v) { int nTerms = terms.length; int i; double value=0; for (i=0; i<nTerms; i++) { value += terms[i].Evaluate(v); } return value; } // continued in next slide

29 Example: polynomial public Polynomial Add (Polynomial p) { Polynomial q = null; AlgebraicTerm[] aterms; int i; if (checkConsistency(p)) { // Assume ordered terms aterms = new AlgebraicTerm [terms.length]; for (i=0; i<terms.length; i++) { aterms[i] = terms[i].Add (p.GetTerms()[i]); } q = new Polynomial (aterms); } return q; } // continued in next slide

30 Example: polynomial private boolean checkConsistency (Polynomial p) { return (p.GetTerms().length == terms.length); } } // end of polynomial class; continued in next slide

31 Example: polynomial class PolynomialExample { public static void main (String arg[]) { double coeff[] = {1, 2, 1}; int index[][] = {{2}, {1}, {0}}; double values[] = {-2}; Polynomial perfectQ = new Polynomial (coeff, index, 1); coeff[1] = -2; Polynomial perfectQ2 = new Polynomial (coeff, index, 1); Polynomial oneMoreQ = perfectQ.Add (perfectQ2); // continued in next slide

32 Example: polynomial swap (perfectQ, perfectQ2); System.out.println (perfectQ.Evaluate(values) + “, ” + perfectQ2.Evaluate(values)); } // end main // following method doesn’t work /* private static void swap (Polynomial P1, Polynomial P2) { AlgebraicTerm terms[] = P1.terms; P1.terms = P2.terms; P2.terms = terms; }*/ // continued in next slide

33 Example: polynomial // Note that swap must be static because // it is called by a static method private static void swap (Polynomial P1, Polynomial P2) { AlgebraicTerm terms[] = P1.GetTerms(); P1.SetTerms (P2.GetTerms()); P2.SetTerms (terms); } } // end class

34 Announcements Reminder: exam on 9 th October No tutorial and no lab next week There is a class on 11 th October

35 String argument Strings are objects –Passed by reference value But strings cannot modified –Every string operation creates a new string Consider the following Java class class StringTester { public static void main (String arg[]) { String s = “abcd”; ModifyString (s); System.out.println (“From main: ” + s); } // Continued in next slide

36 String argument public static void ModifyString (String s) { s += “e”; System.out.println (“From ModifyString: ” + s); } The output is as follows From ModifyString: abcde From main: abcd

37 String argument The change is reflected only within ModifyString –The concatenation operation creates a new string and stores “abcde” in that –Assigns this new string to s –Addresses of s before and after the concatenation are different –Original string s remains unchanged with contents “abcd”