Java Classes and Methods - Ken Williams home...

55
Java Classes and Methods COMP163 Introduction to Computer Programming

Transcript of Java Classes and Methods - Ken Williams home...

Page 1: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Java Classesand Methods

COMP163 Introduction to Computer Programming

Page 2: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

“Our object in the construction of the

state is the greatest happiness of the

whole, and not that of any one class.”

Plato

Page 3: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Dropping a Course

• Today, Monday, October 28 is the last day to drop a course

• At A&T you may drop up to 5 courses while an undergrad

• You may only repeat 5 courses while an undergrad

• You can only attempt a course 3 times

• If you drop a course, it appears as a "W" on your transcript, but does not effect your GPA

• It would be better to withdraw than flunk

Page 4: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

ZyBooks Reading

• Read sections 8.1 to 8.4 and 8.6 to 8.12

• Answer all of the participation questions

• Due by midnight on Wednesday, October 30

Page 5: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Two Parts of Method

static int cube ( int cat ) { // headingint dog = cat*cat*cat ;

return dog ;

}

} // body

Page 6: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

What is in a heading?

static int cube ( int mouse ) {

type of value

returned

name of

methodparameter listmodifiers

(optional)

Page 7: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Parameters Must Match Type• Methoddouble myfunc( int cat, String dog){

… }

• Calling programint cow = 3;

String bull = "moo";

double goat;

goat = myfunc( cow, bull );

Page 8: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Variable Type

• In the method header, you need to specify the variable type

int myFunc( int trout, double salmon)

• When you call the method, you do not need to specify the type of the parameters

int fish, cow = 47;

fish = myFunc( cow, 3.13 );

Page 9: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Type but not Name

• When calling a method, the type of the arguments passed to the method must match the type of parameters in the method header

• The names of the arguments and methods do not have to match

int myFunc( int trout, double salmon)

int fish, cow = 47;

fish = myFunc( cow, 3.13 );

Page 10: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Argument Values Copied

• When a method call is executed, the values of the argument variables (or constants) are copied to the parameter variables

• The method uses a copy of the argument variables

Page 11: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Parameter Values Copied

public class PassParm {

public static void main(String[] args ){

int cat = 5, bull = 7, dog = 1;

dog = doIt( cat, bull );

System.out.println("main "+dog);

}

static int doIt( int ant, int bug ) {

System.out.println("doIt"+ant+" "+bug);

return ant + bug;

}

} Displays: doIt 5 7

main 12

Page 12: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Write a method with your team

• Write a method that takes a radius as a double parameter and returns the area of a circle with that radius

The area is 𝜋𝑟2

Page 13: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Possible Solution

• Write a method that takes a radius as a double parameter and returns the area of a circle with that radius

double area( double r ) {

return Math.PI * r * r;

}

Page 14: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Accessing Object Fields

• The instance variables of an object can be used by any method of that object just like a variable defined in the method

public class Student {private int identifier;public double grade;public String name;public void setGrade(double score) {

grade = score;}

}

Page 15: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

What is displayed?

A. tryit 10 main 6

B. main 10 tryit 6

C. tryit 10 main 7

D. main 2 tryit 10

public static void main (String[] eel) {

int cat = 7, dog = 2;

dog = tryit( cat );

System.out.println("main "+dog);

}

int tryit( int cow ) {

int goat = cow + 3;

System.out.print("tryit "+ goat );

return cow - 1;

}

Page 16: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Access Outside the Class

• Public instance variables can be accessed from outside of the class

• To access a instance variable, write the object name, a period and then the instance variable’s name

Student fred = new Student();

fred.name = "Fred Smith";

System.out.println( fred.grade * Math.PI);

Page 17: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Access Rights

Data values or methods can be used if specified:

• public – anywhere

• private – only in that class

• protected – only in that class or any class that extends it

• nothing – only in that package

Page 18: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Private examplepublic class Student {

public int id;

private double grade;

public String name;

public void setGrade(double score) {

grade = score;

}

public double getGrade() {

return grade;

}

}

Page 19: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Accessing the Example• In another class, you can access the public but

not the private values

public class myProg {

public static void main(String[] x ) {

Student mary = new Student();

mary.name = “Rosemary”;

mary.grade = 4.0; // not allowed

mary.setGrade( 4.0 ); // allowed

}

}

Page 20: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Data Abstraction

• Classes are described by their interface, that is, what they can do and how they are used

• The internal data and operation are hidden

• In this way if the internal operation is changed, programs using the class will not be impacted as long as the interface remains consistent

Page 21: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Accessing public Instance Values

public class Person {private double height, weight;public double bmi;// other data and method are not shown

}

// in another programPerson couchPotato = new Person();double size = couchPotato.bmi;

Page 22: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Accessing Instance Values by get Method

public class Person {private double height, weight;public double bmi;public double getBMI() {

return bmi;}// other data and method are not shown

}

// in another programPerson couchPotato = new Person();double size = couchPotato. getBMI();

Page 23: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Accessing Instance Values by a Method

public class Person {private double height, weight;

public double getBMI() {return weight*703.0/(height*height);

}// other data and method are not shown

}

// in another programPerson couchPotato = new Person();double size = couchPotato. getBMI();

Page 24: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Private or Public

• Class instance variables should be made private unless there is a need to make them public

• When class instance variables are private, you know they will not be changed by some other part of the program

• In many programs, package access (not specifying access rights) works about the same as public

• Specifying a variable as public should indicate that you expect it to be accessed elsewhere

Page 25: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

What is displayed?

A. 3

B. 5

C. 7

D. 8

E. Error

public class Student {

public int id = 2;

public double getIdPlus() {

return id + 5;

}

}

// in another program

Student dog = new Student();

dog.id = 3;

int cat = dog.getIdPlus();

System.out.println( cat );

Page 26: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Method Purpose

• Constructors

– Initialize an object

• Modifiers

– Change the values of an object

• Accessors

– Return the value of a object without changing anything

• Function

– Compute some value or perform some action

Page 27: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Constructors

• A constructor method is automatically called when an object is created

• The name of the constructor method is always the same as the class name

• Constructors can be used to initialize the values of an object’s variables

• Constructors may or may not have parameters

• Constructors do not have a return type. They are not void

Page 28: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Constructor Example

public class Widget {

private int count = 0;

/* constructor method */

public Widget( int aardvark) {

count = aardvark;

}

}

Page 29: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Using Constructors

• The constructor method is called when you create an object

Widget gorilla;

gorilla = new Widget( 5 );// constructor

Page 30: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Tryit

public class Rodent{

double rat;

int mouse;

// Write a constructor method to initialize// the class variables

}

// in another program using the Rodent class

Rodent mole = new Rodent( 5.6, 14 );

Rodent gerbil = new Rodent( 3.25, 8 );

Page 31: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Possible Constructorpublic class Rodent{

double rat;

int mouse;

public Rodent( double vole, int shrew ) {

rat = vole;

mouse = shrew;

}

}

// in a program using the Rodent class

Rodent mole = new Rodent( 5.6, 14 );

Rodent gerbil = new Rodent( 3.25, 8 );

Page 32: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

this

• The Java keyword “this” means this object

• You can use this to access anything of the object, but not static variables of the class

• If you have a field named xyz, then you can access the field as this.xyz

Page 33: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Another Constructor Example

public class Widget {

private int count = 0; // field variable

/* constructor method */

public Widget( int count ) { // parameter

this.count = count;

}

}

Page 34: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Constructors are Usually Simple

• Most constructor methods simply copy the parameter to an instance variable

• Some constructors set instance variables to a constant

• Some constructors are more complex. The constructor for Scanner may have to check on a network connection

Page 35: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Default Constructor• If you do not write a constructor method, Java will assume

a default constructor exists

• The default constructor creates the object, but does not initialize any values

• The default constructor has no parameters

public class Widget {private int count;public Widget() { // default constructor}

}

Page 36: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Any Constructor Removes the Default

• If you write a constructor method for a class, Java will no longer use the default constructor

public class Widget {private int count;public Widget(int num) {

count = num;}

}

Widget cat = new Widget( ); // does NOT work

Page 37: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Multiple Constructors

• A class may have more than one constructor

• Different constructors must have a different number or type of parameters

• All constructors must have the same name as the class

• Having multiple methods with the same name is known as polymorphism

Page 38: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Two Line Constructorspublic class Line {

double slope; // slope of the line

double intercept; // Y intercept of the line

public Line(double tilt) { // constructor

slope = tilt;intercept = 0.0;

}public Line(double tilt, double y) { // constructor

slope = tilt;intercept = y;

}}

Page 39: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Polymorphism Requires Different Parameters

• You cannot have the following two methods because they both have one double parameter

public Line(double tilt) { // ERROR Same as below

slope = tilt;

intercept = 0.0;

}

public Line(double yAxis) { // ERROR Same as above

slope = 1.0;

intercept = yAxis;

}

Page 40: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Restoring the no parameter constructor

• You can write a constructor with no parameters

public class Widget {private int count;public Widget(int num) {

count = num;}public Widget( ) {

count = 0;}

}

Widget cat = new Widget( ); // now this works

Page 41: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Getters and Setters

• Some methods are very simple and only return or set an instance variable

int rabbit; // instance variable

int getRabbit() {

return rabbit;

}

void setRabbit(int hare) {

rabbit = hare;

}

Page 42: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Accessor Methods

• Accessor methods return some value from the object

• Accessor methods do not usually change anything in the object

• Examples of accessor methods include:

– String length() method

Page 43: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Modifier Methods

• Modifier methods change the state of an object

• A modifier method may just set the value of a single variable or may perform a lengthy sequence of actions

• Modifier methods are often void methods

Page 44: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Example Classpublic class Widget {

private int count = 0; // class data value

public Widget( int num ) { // constructorcount = num;

}public void inc() { // method to increment

count++;}public int getCount() { // accessor method

return count;}public void setCount( int value ) { // modifier method

count = value;}

}

Page 45: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

What is displayed?

A. 3

B. 4

C. 7

D. 8

Widget cow = new Widget( 3 );

cow.setCount( 7 );

cow.inc( );

int bull = cow.getCount( );

System.out.println( bull );

Page 46: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Naming Convention

• Class names start with an uppercase letter

• Objects are written in lowercase

• Method names are in lowercase

• Constructors must have the same name as the class

• Accessor methods often have names that can be used as nouns or getVariable

• Modifier methods often have names that can be used as verbs or setVariable

Page 47: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Calling Methods

• In Java you can use a method of an object by writing the object’s name, a period, the name of the method

Widget thing = new Widget();

thing.setCount( 5 );

• This calls the setCount method of Widget object thing passing it an integer 5 as a parameter

Page 48: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Objects as Parameters

• Any data type, simple or object, can be a parameter to a method

• Consider a method that adds the count from one Widget object to another

public void addCount( Widget cow ) {

count = count + cow.getCount();

}

Page 49: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Inheritance

• You can extend an existing class to add new features

• We used inheritance to extend JFrame

• The new class has all of the data values and methods of the parent classes

Page 50: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Inheritance Example

• Some of our programs have input numbers from JTextField objects

• The getText method of JTextField only returns a string

• We can extend JTextField to add methods to get a double or an int

Page 51: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Extending JTextField

public class NumField extends javax.swing.JTextField {

public int getInt() {

String text = getText();

int number = Integer.parseInt(text);

return number;

}

public double getDouble() {

String text = getText();

double number = Double.parseDouble(text);

return number;

}

}

Page 52: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Using NumField// class variables at the beginning

NumField inYear = new NumField();

NumField inLoan = new NumField();

...

public void actionPerformed(

java.awt.event.ActionEvent thing) {

double loan = inLoan.getDouble();

double m = inYear.getDouble() * 12.0;

double pay = loan * etc.;

answer.setText("Monthly payments of $"+pay);

}

Page 53: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Parent Method Available

• You do not need the Java source code of a class to inherit from it

• You can extend a system class

• All of the original methods are available

NumField inYear = new NumField();

inYear.setText("default");

Page 54: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

ZyBooks Reading

• Read sections 8.1 to 8.4 and 8.6 to 8.12

• Answer all of the participation questions

• Due by midnight on Wednesday, October 30

Page 55: Java Classes and Methods - Ken Williams home pagewilliams.comp.ncat.edu/COMP163/ClassesMethods.pdf · Java Classes and Methods COMP163 Introduction to Computer Programming “Our

Dropping a Course

• Today, Monday, October 28 is the last day to drop a course

• At A&T you may drop up to 5 courses while an undergrad

• You can only repeat 5 courses while an undergrad

• You can only attempt a course 3 times

• If you drop a course, it appears as a "W" on your transcript, but does not effect your GPA

• It would be better to withdraw than flunk