400 likes | 491 Views
Java Classes. Chapter 1 . Chapter Contents. Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining a Java Class Passing Arguments Constructors Static Fields and Methods Packages – The Java Class Library. Classes.
E N D
Java Classes Chapter 1
Chapter Contents • Objects and Classes • Using Methods in a Java Class • References and Aliases • Arguments and Parameters • Defining a Java Class • Passing Arguments • Constructors • Static Fields and Methods • Packages – The Java Class Library
Classes • A class is a type or kind of object • A class definition is a general description of • What the object is • What it can do • Objects of the same class have • The same kinds of data • The same methods Blueprint for constructing objects
Objects • An object is a program construct that • Contains data • Performs certain actions • The actions are called methods • The actions interact to form the solution to a given problem
An Example of a Class An outline of a class
Instantiation of the Class Three instances of the class Automobile
Create a object for a Java Class • Declare:Name joe; • Instantiate: joe = newName(); • Combine: Name joe = new Name(); • The new operator creates an instance of the class • Invokes the constructor method
Create a object for a Java Class A variable that references an object.
References and Aliases • Primitive types:(Built-in to Java) • A chunk of memory holding the data itself • byte, short, int, long float, double, char, boolean • int number1; • All other types are reference or class types • All objects defined from classes • The object “refers to” or “points to” the chunk of memory that actually holds the data • String greeting = "Howdy"; • greeting is a reference variable instead of the actual string • Set to null value for an reference-variable • When two variables reference the same instance, they are considered aliases
References and Aliases • Name jamie = new Name(); • jamie.setFirst(“Jamie”); • jamie.setLast(“Jones”); • Name friend = jamie; • Two references, one chunk of data • Is friend == jamie? Aliases of an object
Method Definitions • Given • This is a valued method • Returns a String • Given • This is a void method public String getFirst() { return first; } // end getFirst public void setFirst(String firstName) { first = firstName; } // end setFirst
Arguments and Parameters • Given statements:Name joe = new Name();joe.setFirst ("Joseph");joe.setLast ("Brown"); • "Joseph" and "Brown" are arguments sent to the methods • Arguments must correspond to the formal parameters in the method declaration public void setFirst(String firstName) { First = firstName; }
Defining a Java Class public class Name { private String first; // first nameprivate String last; // last name < Definitions of methods are here. > } // end Name • Given • Store class definition in a file whose name is the name of the class followed by .java. • public, private: access modifier • class Name is public, any other Java class can use this class • private data fields (instance variables) • Note data fields are private: only the methods inside this class can access them. All data fields should be private • They will require accessor and mutator methods
Coding Conventions • Naming conventions • conventions are things we suggest to make code more consistent and easier to understand • this is purely aesthetic; not enforced by the compiler • We use capitalization to distinguish an identifier’s purpose • class names begin with uppercase letters: Use noun or descriptive phrase • method, variable names begin with lower case: Use verb or action phrase • instance variables start with an underscore Good Name Student takeClass _cs220Student Poor Name Thing (no role, purpose) doStuff (not specific) c (too cryptic) Class Method object
Passing Arguments • Call by value • For primitive type, formal parameter initialized to value of corresponding argument in call. Method cannot change the value of the argument. • Call by reference • For a reference type, formal parameter is initialized to the memory address of the object in the call. Method can change the data in the object.
Example 1 public void giveLastNameTo(Name child) { child.setLast(last); } public static void main(String[] args) { Name jamie = new Name(); jamie.setFirst(“Jamie”); jamie.setLast(“Jones”); Name jane = new Name(); jane.setFirst(“Jane”); jane.setLast(“Doe”); jamie.giveLastNameTo(jane); }
Passing Arguments The method giveLastNameTo modifies the object passed to it as an argument.
Passing Arguments The method giveLastNameTo modifies the object passed to it as an argument.
Example 2 Public void giveLastNameTo(Name Child) { String firstName = child.getFirst(); child = new Name(); child.setLast(last); child.setFirst(firstName); } Public static void main(String[] args) { Name jamie = new Name(); jamie.setFirst(“Jamie”); jamie.setLast(“Jones”); Name jane = new Name(); jane.setFirst(“Jane”); jane.setLast(“Doe”); jamie.giveLastNameTo(jane); }
Passing Arguments A method cannot replace an object passed to it as an argument.
Passing Arguments A method cannot replace an object passed to it as an argument.
Constructors • A method that • Allocates memory for the object • Initializes the data fields • Properties • Same name as the class • No return type, not even void • Any number of formal parameters including no parameters • Default constructor has no parameters
Constructors public Name() public Name(String firstName, String lastName) { { setFirst(firstName); setLast(lastName); } } Name jill = new Name(“Jill”, “Jones”); jill = new Name(“Jill”, “Smith”); An object (a) after its initial creation; (b) after its reference is lost memory leak
Static Fields and Methods • A data field that does not belong to any one object • Adding reserved word static: • private static int numOfInvocation = 0; • Also called:static field, static variable, class variable • One copy of that data item exists to be shared by all the instances of the class
Static Fields • Static does not mean constant, shared by all objects of its class, but value can change. Objects can use a static field to communicate with each other to perform some joint action. • private static int numberOfInvocations = 0; A static PI versus a non static field
Static Methods • A method that does not belong to an object of any kind. • You use the class name instead of an object name to invoke the method. • Java predefined class math contains standard mathematical methods. • int maximum = Math.max(2,3); • double root = Math.sqrt(4.2); • Static method cannot access non-static fields, nor non-static methods. • Constructors cannot be static.
Packages • Multiple related classes can be conveniently grouped into a package • Begin each file that contains a class within the packagepackage myStuff; • Place all files within a directory • Give folder same name as the package • Package can contain packages • To use the package, begin the program with import myStuff.graphics.*; myStuff.graphics.Frame package names class name
The Java Class Library • Many useful classes have already been declared • Collection exists in Java Class Library • Example • The class Math is part of the package java.lang