Sie sind auf Seite 1von 5

OOP 2.

Data - Student Class


Purpose of this lesson: Classes versus objects. How to create objects and assign values to the instance variables (fields).

Style: One class per file is the standard.

New Java language features Using new to create an object. eferencing fields using dot notation.

One class per file is standard practice


Here is the class again that represents infor!ation about a student. "ypically there is one class definition per file# so this would be stored in Student1.java.
// File : oop/dataclass/Student1.java // Purpose: Information about a student. public class Student1 { public String firstName public String lastName public int id " // First name // !ast name // Student id

Class versus object


$ class is the te!plate that defines what data is in an object. "here is one class definition# fro! which you can create !any objects containing those fields using the new %eyword. "here are several analogies that !ight be useful. Coo ie cutter and coo ies. $ coo%ie cutter is li%e a class definition. &t isn't a coo%ie# but can be used to create a coo%ie. (ach coo%ie can will have the sa!e attributes (shape)# but each coo%ie can have different values for the attributes (type of dough# thic%ness# ...). Dog and !ido. "he concept of )og is li%e a class# but there are !any possible instances of this class# eg# !y dog *ido# or your dog over. !or" sta"p and filled out for"s. "here are rubber in%pad sta!ps that are used to sta!p out a s!all for!. "hese have been used in several places in !y passport# where passport control sta!ped !y passport# then filled out the fields with the date# how long & could stay# etc. "he rubber sta!p is li%e a class# defining the fields. "he filled out for! in each passport are the objects# with specific values for each field.

#se new to create a new object

$ class defines what fields an object will have when it's created. +hen a new Student, object is created# a bloc% of !e!ory is allocated# which is big enough to hold these three fields -- as well as so!e e.tra overhead that all objects have.
Student1 tatiana tatiana # new Student1$% // &reate Student1 object wit' new.

$new$ and parentheses


"o create a new object# write new followed by the na!e of the class (eg# Student1)# followed by parentheses. /ater we'll see that we can specify argu!ents in the parentheses when creating a new objects.

%ccess public instance variables with dot notation


"he instance variables (firstName# lastName# id) na!e data which is stored in each object. $nother ter! for instance variable is field. $ll public fields can be referenced using dot notation (later we'll see better ways to access and set fields). "o reference a field# write the object na!e# then a dot# then the field na!e.
Student1 tatiana object. // (eclare a variable to 'old a Student1

//... &reate a new Student1 object for )atiana. tatiana # new Student1$% // &reate a new Student1 object wit' default values. tatiana.firstName # *)atiana* // Set values of t'e fields. tatiana.lastName # *+o'nson* tatiana.id # ,,-./01 +2ptionPane.s'ow3essage(ialog$null4 *2ne student is named: * 5 tatiana.lastName 5 *4 * 5 tatiana.firstName%

Awkward? "his si!ple e.a!ple with one student is so!ewhat aw%ward# but we'll get to e.a!ples that show real advantages soon.

% class definition is a te"plate for creating objects


$ class defines which fields an object has in it. 0ou need to use new to create a new object fro! the class by allocating !e!ory and assigning a default value to each field. $ little later you will learn how to write a constructor to control the initiali1ation. &t's not very interesting to create only one object of class# so the following e.a!ple creates a couple of the!.
// 1 1 File : oop/dataclass/)estStudent1.java

import java6.swing.7

8 0 9 : /

public class )estStudent1 { public static void main$String;< args% { Student1 tatiana Student1 pupil //... &reate new Student1 object wit' new. tatiana # new Student1$% tatiana.firstName # *)atiana* tatiana.lastName # *+o'nson* tatiana.id # ,,-./01

//... &reate anot'er Student1 object. pupil # new Student1$% , pupil.firstName # +2ptionPane.s'owInput(ialog$null4 *First name*% pupil.lastName # +2ptionPane.s'owInput(ialog$null4 *!ast name*% 1. pupil.id # Integer.parseInt$+2ptionPane.s'owInput(ialog$null4 *I(*%% 11 +2ptionPane.s'ow3essage(ialog$null4 *2ne student is named: * 11 5 tatiana.lastName 5 *4 * 5 tatiana.firstName 5 *=n and anot'er is named: * 18 5 pupil.lastName 5 *4 * 5 pupil.firstName% " 10 " 119 1: 1/ 1, 1. 11 11 18 10 119 1:

OOP &. Constructor - Student Class

Purpose of this lesson: "o introduce the concept of constructors. 2urpose of constructors is both guaranteed initiali1ation and convenience. New Java language features Constructor synta. - li%e a !ethod but with class na!e and i!plicit type3value.

%dd a constructor for better initiali'ation


%void bad initiali'ations. One proble! with the Student, class is that the user has to e.plicitly initiali1e all fields. "his re4uires e.tra typing# but !ore i!portantly# it is errorprone. &f we forget to initiali1e a field# the default value could have bad conse4uences. Convenience. )efining a constructor !a%es creation of an object easier to write.

Constructor S(nta)
Si"ilar to "ethod. $ constructor is si!ilar to a !ethod -- it's called li%e a !ethod# has para!eters li%e a !ethod# and it returns. 5ut it !ust have the sa!e na!e as the class for which it is a constructor. $lso# the type and return value are i!plicit.

Student2 e)a"ple with a constructor


Here is the Student, class with a constructor which si!ply initiali1es the fields (instance variables) fro! its para!eters. Often constructors do !ore wor% in initiali1ation# including chec%ing for legal values# but for now we'll just si!ply copy the para!eter values.
// File : oop/dataclass/Student1.java // Purpose: Information about a student. (efines constructor. public class Student1 { public String firstName public String lastName public int id // First name // !ast name // Student id

//######################################## constructor public Student1$String fn4 String ln4 int idnum% { firstName # fn lastName # ln id # idnum " "

6ote that a constructor has no return type and the na!e is the sa!e as the class na!e.

#sing the constructor

Here is the first progra! rewritten to use the above class definition with a constructor.
1 // File : oop/dataclass/)estStudent1.java 1 // Purpose: )ests Student1 constructor. 8 0 import java6.swing.7 9 public class )estStudent1 { : public static void main$String;< args% { / Student1 tatiana , Student1 pupil 1. 11 //... &reate new Student1 object wit' new. 11 tatiana # new Student1$*)atiana*4 *+o'nson*4 ,,-./01% 18 10 //... &reate anot'er Student1 object. 1String first # +2ptionPane.s'owInput(ialog$null4 *First name*% 19 String last # +2ptionPane.s'owInput(ialog$null4 *!ast name*% 1: int studI(# 1/ Integer.parseInt$+2ptionPane.s'owInput(ialog$null4 *I(*%% 1, pupil # new Student1$first4 last4 studI(% 1. 11 +2ptionPane.s'ow3essage(ialog$null4 *2ne student is named: * 11 5 tatiana.lastName 5 *4 * 5 tatiana.firstName 18 5 *=n and anot'er is named: * 10 5 pupil.lastName 5 *4 * 5 pupil.firstName% 1" "

*hen there+s an e)plicit constructor, there+s no default constructor


if you define a constructor in a class# the 7ava co!piler no longer auto!atically creates a default (para!eterless) constructor. $ll object creation therefore !ust use your e.plicitly defined constructor. *or e.a!ple#
Student1 someone someone # new Student1$% // I!!>?@!. )'ere is no default constructor. someone # new Student1$*3ic'ael*4 *3aus*4 1% // 2A. 3ust specifB 8 values.

"he constructor can chec% that all fields are defined with legal values. +e're not going to e.tend the Student8 class any further to test for legal values# but we will in the ne.t e.a!ple. *or the !o!ent we'll leave the Student class# and !ove to so!ething different to show the sa!e ideas.

Das könnte Ihnen auch gefallen