JAVA METHODS and CONSTRUCTORS. 2 JAVA Classes The class is the fundamental concept in JAVA (and other OOPLs) A class describes some data object(s), and.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

***** SWTJC STEM ***** Chapter 4-1 cg 42 Object Oriented Program Terms Up until now we have focused on application programs written in procedural oriented.
JAVA METHODS and CONSTRUCTORS. 2 JAVA Classes The class is the fundamental concept in JAVA (and other OOPLs) A class describes some data object(s), and.
Inheritance, part 2: Subclassing COMP 401, Fall 2014 Lecture 8 9/11/2014.
Road Map Introduction to object oriented programming. 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,
Starting Classes and Methods. Objects have behaviors In old style programming, you had: –data, which was completely passive –functions, which could manipulate.
EEC-681/781 Distributed Computing Systems Java Tutorial Wenbing Zhao Cleveland State University
Sub and superclasses using extends
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Java Objects and Classes. 3-2 Object Oriented Programming  An OO program models the application as a world of interacting objects.  A typical Java program.
UMBC CMSC 331 Java JAVA BASICS. UMBC CMSC 331 Java 2 Comments are almost like C++ The javadoc program generates HTML API documentation from the “javadoc”
Lecture 3 Casting Abstract Classes and Methods Interfaces.
Chapter 4 Objects and Classes.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Basic Object- Oriented Concepts Presented By: George Pefanis 21-Sep-15.
Internet Software Development Classes and Inheritance Paul J Krause.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
NSIT,Jetalpur CORE JAVA CONCEPTS SURABHI MISHRA (LCE)NSIT.
CS 363 Spring 2004 Elizabeth White CS 363 Comparative Programming Languages Java.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
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 3 Introduction to Classes and Objects Definitions Examples.
Classes Modeling the Object. Objects model the world Classes are programmer defined types that model the parts of a system Class serve as blueprints for.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
A Java program consists of a set of class definitions, optionally grouped into packages. Each class encapsulates state and behavior appropriate to whatever.
Introduction To Objects Oriented Programming Instructor: Mohammed Faisal.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
Topics Instance variables, set and get methods Encapsulation
OOP Basics Classes & Methods (c) IDMS/SQL News
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
Comp1004: Building Better Objects II Encapsulation and Constructors.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
2-Oct-16 Basic Object-Oriented Concepts. 2 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions,
Topic: Classes and Objects
JAVA METHODS and CONSTRUCTORS
Inheritance and Polymorphism
Chapter 3: Using Methods, Classes, and Objects
03/10/14 Chapter 9 Inheritance.
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
CSC 143 Inheritance.
Chapter 9 Inheritance and Polymorphism
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Core Concepts.
JAVA BASICS.
Final and Abstract Classes
JAVA BASICS.
Chapter 11 Inheritance and Encapsulation and Polymorphism
CSG2H3 Object Oriented Programming
Chengyu Sun California State University, Los Angeles
Presentation transcript:

JAVA METHODS and CONSTRUCTORS

2 JAVA Classes The class is the fundamental concept in JAVA (and other OOPLs) A class describes some data object(s), and the operations (or methods) that can be applied to those objects Every object and method in Java belongs to a class Classes have data (fields) and code (methods) and classes (member classes or inner classes) Static methods and fields belong to the class itself Non-static methods and fields belong to instances

3 An example of a class Type it into jGrasp and run it public class Person { private String name; private int age=-1; public Person() {name=“ “; age=0;} public void birthday ( ) { age++; System.out.println (name + “ is now “ + age); } } Instance Variable Method

Why didn’t it run? 4 What is missing from our Person class? What kind of error did you get? How can we fix it? Create a PersonTester class with a main() and construct two people. How old are they? How do you make them older? What might make this nicer?

Another Constructor Add this to your Person class 5 // new constructor public Person(int currAge) { this.age = currAge; } //existing constructor public Person() { this.age = 0; this.name = “ “; }

6 Constructors Classes should define one or more constructors Their name is the same as the class name Constructors are differentiated by the number and types of their arguments –An example of overloading If you don’t define any constructors at all, a default one will be created. Constructors automatically invoke the zero argument constructor of their superclass when they begin

What Happens? 7 public static void main(String[] args) { Person dhruval = new Person(); Person blayde = new Person(16); dhruval.birthday(); blayde.birthday(); } void birthday ( ) { age++; System.out.println (name +” is now “+ age); }

What Happens? 8 public static void main(String[] args) { Person hayden = new Person(); Person denzil = new Person(16); hayden = denzil; hayden.birthday(); }

What Happens? 9 public static void main(String[] args) { Person aria = new Person(); Person zander = aria; Person quen; aria = zander; quen.birthday(); aria.birthday(); }

What about the name? 10 Do we have any way to set the name instance variable? What do we need to do? Create a new method: public void setName( String nm) { this.name = nm; }

Or we could create a new constructor or two: 11 public Person( String nm) { this.name = nm; } public Person( String nm, int age) { this.name = nm; this.age = age; }

Best Practice 12 Create methods to get and set every instance variable. Why? private variables, public methods We call them accessors and mutators, or informally, getters and setters Exception: instance variables that you don’t want set by any other class

13 Methods, arguments and return values Java methods. General case: returnType methodName ( arg1, arg2, … argN) { methodBody } The return keyword exits a method optionally with a value int storage(String s) {return s.length() * 2;} boolean flag() { return true; } float naturalLogBase() { return 2.718f; } void nothing() { return; } void nothing2() {}

Instance Variables Java instance variables. General case: variableType variableName Can declare and initialize in one statement or two String name; name = “APCSA”; String name = “APCSA”; int age = -1; 14

Now What Happens? 15 public static void main(String[] args) { Person josh = new Person(); Person andrew = new Person(“Karthik”, 17); josh.setName(“Kayleigh”); Kayleigh.birthday(); }

What Happens? 16 public static void main(String[] args) { Person wade = new Person(); Person chris = new Person(“Alena”); wade = chris; chris.birthday(); chris.birthday(“Hemant”); }

What Happens? 17 public static void main(String[] args) { Person tyler = new Person(“Tyler”); Person matthew; Person faith = new Person(“Dill”, 15); Person josh = tyler; matthew = “Tyler”; faith.setName(“Faith ” + this.name); matthew.birthday(); }

18 Scoping Scope is determined by the placement of curly braces {}. A local variable defined within a scope is available only to the end of that scope. { int x = 12; /* only x available */ { int q = 96; /* both x and q available */ } /* only x available */ /* q “out of scope” */ }

19 Scope of Objects Java objects don’t have the same lifetimes as primitives. When you create a Java object using new, it hangs around past the end of the scope. Here, the scope of variable s is delimited by the {}s but the String object hangs around until GC’d { String s = new String("a string"); } /* end of scope */

20 The static keyword Java methods and variables can be declared static These exist independent of any object This means that a Class’s –static methods can be called even if no objects of that class have been created and –static data is “shared” by all instances (i.e., one value per class instead of one per instance class StaticTest {static int i = 47;} StaticTest st1 = new StaticTest(); StaticTest st2 = new StaticTest(); // st1.i == st2.i == 47 StaticTest.i++; // or st1.I++ or st2.I++ // st1.i == st2.i == 48

21 Another Constructor example public class Circle { public static final double PI = ; // A constant private double r; // instance field holds circle’s radius // The constructor method: initialize the radius field public Circle(double r) { this.r = r; } // Constructor to use if no arguments public Circle() { r = 1.0; } // The instance methods: compute values based on radius public double circumference() { return 2 * PI * r; } public double area() { return PI * r*r; } } this.r refers to the r field of the class

Bicycle Class – Instance Variables public class Bicycle { private int cadence; private int gear; private int speed; 22

Bicycle Class - Constructors public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } 23

Bicycle Class - Methods public void setCadence(int newValue) { cadence = newValue; } public void setGear(int newValue) { gear = newValue; } public void applyBrake(int decrement) { speed -= decrement; } 24

Bicycle Class – Closing Bracket } 25

Bicycle Class – With Static 26 public class Bicycle { private int cadence; private int gear; private int speed; private int id; private static int numberOfBicycles = 0;

27 public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; id = ++numberOfBicycles; } public int getID() { return id; } public static int getNumberOfBicycles() { return numberOfBicycles; }

public int getCadence() { return cadence; } public void setCadence(int newValue) { cadence = newValue; } public int getGear(){ return gear; } 28

29 public void setGear(int newValue) { gear = newValue; } public int getSpeed() { return speed; } public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; }

30 Extending a class Class hierarchies reflect subclass-superclass relations among classes. One arranges classes in hierarchies: –A class inherits instance variables and instance methods from all of its superclasses. Musical Instrument -> StringInst -> Viola –You can specify only ONE superclass for any class. Something like multiple inheritance can be done via interfaces (more on this later) What’s the superclass of a class defined without an extends clause?

31 public class MountainBike extends Bicycle { // the MountainBike subclass has one field public int seatHeight; // the MountainBike subclass has one constr public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) { super(startCadence, startSpeed, startGear); seatHeight = startHeight; } // the MountainBike subclass has one method public void setHeight(int newValue) { seatHeight = newValue; }

MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it (mountain bikes have seats that can be moved up and down as the terrain demands). 32

33 Extending a class public class PlaneCircle extends Circle { // We automatically inherit the fields and methods of Circle, // so we only have to put the new stuff here. // New instance fields that store the center point of the circle private double cx, cy; // A new constructor method to initialize the new fields // It uses a special syntax to invoke the Circle() constructor public PlaneCircle(double r, double x, double y) { super(r); // Invoke the constructor of the superclass, Circle() this.cx = x; // Initialize the instance field cx this.cy = y; // Initialize the instance field cy } // The area() and circumference() methods are inherited from Circle // A new instance method that checks whether a point is inside the circle // Note that it uses the inherited instance field r public boolean isInside(double x, double y) { double dx = x - cx, dy = y - cy; // Distance from center double distance = Math.sqrt(dx*dx + dy*dy); // Pythagorean theorem return (distance < r); // Returns true or false }

34 Overloading, overwriting, and shadowing Overloading occurs when Java can distinguish two procedures with the same name by examining the number or types of their parameters. Shadowing or overriding occurs when two procedures with the same signature (name, the same number of parameters, and the same parameter types) are defined in different classes, one of which is a superclass of the other.

35 On designing class hierarchies If you find yourself using the phrase an X is a Y when describing the relation between two classes, then the X class is a subclass of the Y class. Inheritance If you find yourself using X has a Y when describing the relation between two classes, then instances of the Y class appear as parts of instances of the X class. COMPOSITION

36 Data hiding and encapsulation Data-hiding or encapsulation is an important part of the OO paradigm. Classes should carefully control access to their data and methods in order to –Hide the irrelevant implementation-level details so they can be easily changed –Protect the class against accidental or malicious damage. –Keep the externally visible class simple and easy to document Java has a simple access control mechanism to help with encapsulation –Modifiers: public, protected, private, and package (default)

37 Getters and setters A getter is a method that extracts information from an instance. –One benefit: you can include additional computation in a getter. A setter is a method that inserts information into an instance (also known as mutators). –A setter method can check the validity of the new value (e.g., between 1 and 7) or trigger a side effect (e.g., update a display) Getters and setters can be used even without underlying matching variables Considered good OO practice Convention: for variable fooBar of type fbtype, define –getFooBar() –setFooBar(fbtype x)

38 Example getters and setters package shapes; // Specify a package for the class public class Circle { // The class is still public // This is a generally useful constant, so we keep it public public static final double PI = ; private double r; // Radius is private // A method to enforce the restriction on the radius // This is an implementation detail that may be of interest to subclasses protected checkRadius(double radius) { if (radius < 0.0) throw new IllegalArgumentException("radius may not be negative."); } // The constructor method public Circle(double r) { checkRadius(r); this.r = r;} // Public data accessor methods public double getRadius() { return r; }; public void setRadius(double r) { checkRadius(r); this.r = r;} // Methods to operate on the instance field public double area() { return PI * r * r; } public double circumference() { return 2 * PI * r; } }

Assignment P3.4, page 126 – Write an Employee class with two constructors and get/setName() and get/setSalary() methods. Be sure to include a raiseSalary(double byPercent) method. Also write a test program to test your class. 39

40 Abstract classes and methods Abstract vs. concrete classes Abstract classes can not be instantiated public abstract class shape { } An abstract method is a method w/o a body public abstract double area(); (Only) Abstract classes can have abstract methods In fact, any class with an abstract method is automatically an abstract class

41 Example abstract class public abstract class Shape { public abstract double area(); // Abstract methods: note public abstract double circumference();// semicolon instead of body. } public class Circle extends Shape { public static final double PI = ; private double r; // Instance data public Circle(double r) { this.r = r; } // Constructor public double getRadius() { return r; } // Accessor public double area() { return PI*r*r; } // Implementations of public double circumference() { return 2*PI*r; } // abstract methods. } class Rectangle extends Shape { private double w, h; // Instance data public Rectangle(double w, double h) { // Constructor this.w = w; this.h = h; } public double getWidth() { return w; } // Accessor method public double getHeight() { return h; } // Another accessor public double area() { return w*h; } // Implementations of public double circumference() { return 2*(w + h); } // abstract methods. }