Popular in Course
verified elite notetaker
Popular in Electrical Engineering
This 27 page Class Notes was uploaded by Dorris Borer on Monday September 28, 2015. The Class Notes belongs to ESE112 at University of Pennsylvania taught by D.Palsetia in Fall. Since its upload, it has received 16 views. For similar materials see /class/215448/ese112-university-of-pennsylvania in Electrical Engineering at University of Pennsylvania.
Reviews for INTROTOESE
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 09/28/15
Example Bot and BetterBot public class sotr private int x Introduction to Programming private int y wilh Java for Beginners public int getxo public int getY public void eatDot public void move public void turnLeftO public Class BetterBot extends BOt Inheritance public void turnRight turnLeft turnLeft turnLeft 555112 1 Inheritance The extends keyword one Of the W concepts of OOP Inheritance is established via the extends keyword I A hierarchical relationship among classes publlc class Bot I Establishes a superclasssubclass relationship I Establishes is aquot relationships gt eg a BetterBot is aquot Bot public class BetterBot extends Bot Benefits Now we say I Reusability of code I BetterBot inherits from Bot gt Put COde In one Classy use It In a the SUbClasseS gt Based on the visibility modi ers it can inherit and access certain instance variables and methods de ned in Bot gt Revisions only needs to be done in 1 place I A BetterBot is a Bot 39 P ym rphi de Works on many formsquot I BetterBot is a subclasssubtype of Bot gt Write general purpose code designed for a supertype that W orks for a subtypes I Bot Is the supercasssupertype of BetterBot EsE112 2 ESE112 What you inhe s acces ble Inheritance Tree I Visibility modifiers determine which class members are accessible and which do not I Members variables and methods declared with public visibility are accessible and those with pzivate visibility are I Problem How to make classinstance variables visible only to its subclasses I Solution Java provides a thlrd VISIbIIIty modlfler that Java has singe Inheritance each node has one parent helps in inheritance Situations protected Except for Object which has no parent EsE112 A EsE112 The Object Class The toStringO Method By default it returns a string containing an object39s heap address hy By convention it is overrlden to describe the object39s state ss extends Objectquot is impliedimplicit 39 Mos common usage Snugg39m All classes inherit from the Object c ss e bjecl class is the root ofthe class hierarc hen we create a new cla pubhs class Cat l l uss Ptlvate Sttlng model pubhs class Cat extends abjectl l Recall toStrlngO pubhs Catstt1ng model i thlsmode1 model from Rea39VeCtor mlles The Object class has several methods which all object inherit most notably tostringo and equals s u punts Stan tosttlngo semen model ii s model s muss ii s muss EsE112 s EsE112 The equas Method I By default compares heap addresses I By convention it is overriden to match the developer s notion of equa 39ty public class Person private int social social security it private String name public int getSocial return social public boolean equals Person p return thissocial pgetSocial EsE112 Another Example public class Dogl 39vate String name private int age DogString dogName int dogAgeH name dogName age dogAge class BetterDog extends Dogl l EsE112 Constructors and Inheritance gt BetterDog d new BetterDogO I When an object is created its constructor is called I But first a constructor 39om its highest ancestor Object is called then the next highest Dog then its own Better 0 I The default behavior is such that the default noargument constructor is cuted I A constructor can explicitly call its parents its superclass constructor by making a call to super class BetterDog extends Dog public BetterDogString Name int Age superName Age EsE112 Type Rules I A reference variable of type t may hold a value of its own type or any subtype but not of a supertype I Given the following variable declaration Dog b Which of the following assignments are valid new Dog new String new BetterDog new Object c c c c How about these BetterDog bb bb new D b bb new BetterDogO b new Object o ll 1 m s 1 rr r i 1 u EsE112 The Instanceof Operator gt Dog b new Dog gt b instanceof Dog true gt b instanceof Object true gt b instanceof BetterDog false gt BetterDog bb new BetterDog gt bb instanceof BetterDog true gt bb instanceof object true gt bb instanceof Dog true gt Dog bbb new BetterDog a variable can store a subtype gt bbb instanceof BetterDog rue gt bbb instanceof Dog true EsE112 Introduction to Programming WI39fz Java for Beginners Math Class Dynamic vs Static The Math Class I Part of the Java API Application Programming Interface I Collection of common math functions sin cos sqrt etc I And two constants PI and E gt MathPI 3141592853589793 gt a 2718281828459045 gt Mathsqrt25 gtIMathpow210 gt Mathcos0 gtIMathcos2 MathPI 10 555112 1I15 Math Class Description I Notice the phrase javalang at the top of the main panel above the word Math I This means that the Math class is part of the core Java language and hence can be used directly I Math Class Interface I Field Summary Has two constants PI and E I Constructor Summary has no public constructor I Methods Summary many methods all which are static I Method Details eg sqrt takes a double and returns a double 555112 215 How the Math Class is Implemented public class Mathl public static final double PI 3141592653589793 public static double sin double d public static double sqrtdouble d l l l gt MathPI 3 141592653589793 gt Math sqrt 25 50 555112 315 What39s different about Math Class I It s different from OOP class I It is a stateless class I We only need one Math class gtNot multiple instances I No need to instantiate it gtHence no public constructor I All of its variables and methods are static gtstatic means applies to the class as a whole vs applies to an individual instance 555112 ms Dynamic Variables and Methods I All instance variables object data and methods object ehavior created without static keyword I Note There is no dynamic keyword in Java I Dynamic by default I In general dynamic refers to things created at run time ie when the program is running I Every object gets its own dynamic instance variables I Every object effectively gets its own copy of each dynamic metho 555112 5I15 Static Variables I Static means pertaining to the class in general not to an individual object I A variable may be declared outside of a method with the static keyword I Eg static int numTIcketsSold39 I There is one variable numTickets for the class not one per object I A static variable is shared by all instances if any I All instances may be able readwrite it I A static variable that is public may be accessed I Using ClassNamevariableName I Eg MathPl Mathsqrt25 555112 515 Static Method I A method may be declared with the static keyword I Static methods live at class level not at object level I Static methods may access static variables and methods but not dynamic ones I how could it choose which one I Example public static int getNumSold return numTicketsSold 555112 ms Static Methods contd I A static method that is public can be accessed I ClassNamemethodNameargs I double result Mathsqrt250 I int sold TicketgetNumberSold I boolean b isHappy10 555112 8I15 Example Ticket public class Ticketl private static int num39l icketssold o shared private int ticketnum one per object public TicketOl numTicketsSoldH ticketnum num39l icketssold public static int getnumbersoldo return num39ricketssold public int get39l icket ulnbezo return ticketnum public string getInfo return quotticket at 39v ticketnum quot quot num39l icketssold quot tickets soldquot 555112 9I15 Example Ticket contd gt Ticketget umbersold 0 gt Ticket tl new Ticketo gt t1getTicket ullI l gt tlgetlnfo quotticket it 1 l tickets soldquot gt t1getllumbersold gt Ticket t2 new Ticketo gt t2getTicketllullI 2 gt t2getlnfo quotticket it 2 2 tickets soldquot gt quotticket it 1 2 tickets soldquot gt Ticketget umbersold 2 555112 1015 Main method is static I To have standalone Java Application we need a method public static void mainString args I The main method belongs to the class in which it is written I Hence it is static ie does not belong to any object I Note Instance variable cannot be referenced from main unless the object is created 555112 1115 Example public class JustAdd int x int y int 2 public static void mainString args x 5 Y 10 all are wrong 2 x y EsE112 12I15 EsE112 Solution public class JustAdd public static void mainString args JustAdd myAdd new JustA d39 SystemoutprintnmyAddsu 0 public int sumZ y 10 constructor and initializes the Z x y return 2 values Remember that if no constructor 39 is written java creates a default instance variables to their default 13I15 When to use static I A variable should be static if I It logically describes the class as a whole I There should be only one copy of it I A method should be static if I It does not use or affect the object that receives the message it uses only its parameters 555112 1415 EsE112 Static amp Dynamic Rules Recap static variables and methods belong to the class in general not to individual objects The absence of the keyword static before non Iocal variables and methods means dynamic one per objectinstance A dynamic method can access all dynamic and static variables and methods in the same class A static method can not access a dynamic variable How could it choose or which one A static method can not call a dynamic method because dynamic method might access an instance variable 15I15 References Recap I The value of reference variable is I Either null or a heap address Introduction to Programming I null means currently not pointing at any location with Java for Beginners I Counter c new Counter I new Counter allocates space forthe actual Counter on the heap and initializes it I 0 actually allocates space to hold a reference to a Has aquot Relationship c is placed on the stack and existent as long as NUH NUHPomferExceF Ion gt Method does not return if declared in a method Call by Reference gt Dr J Interactions pane is not reset if declared in Interactions pane I The assignment makes 0 refer to the new Counter ESE11Z Has aquot Relationship or Composition I An object of type A has an instance variable which is an H B DormRoom Code object whose type Is B A has a I Eg A Freshman object whose room is of reference type Do mRoom gt DormRoom room new DormRoom208 min gt roomgetLocation 203 Hill gethcadont DormRoom Freshman int number String name public class DormRooml i DormRoom room String builalng private int num private String bldgName ge cName ge tRocm gechcationt public DormRoomint n String b num 11 bldgName b I The UML diagrams show instance variables and methods l of Freshman and DormRoom object I UMLUniversal Modeling Language industry standard used to describe classes in 00 public String getLocation return null quot quot bldgNeue ESE11Z 3 esem Freshman Code A DormRoom on the Heap gt DormRoom room new DormRoom208 quotHillquot Fraahman gt Freshman f new Freshmanujoquot room Stung name Domeoom room gt fQEtNEmeU ujou 39 gamma gt fgetRoomU getLocatien String genieom quot208 Hillquot public class Freshman private String name private normRoom room public Freshmanstring n DormRoom r quotHillquot name n room r gt DormRoom room new DormRoom208 gt room getLocation public String getName return name quot208 Hillquot public DormRoom getRoom return room ESE112 ESE112 A Freshman on the Heap Note on Operators I Dot operator and parentheses for method gt quot mm new quot R 2 B39 111quot gt Freshman f new Freshmanujoquot room calls have same precedence gt Manama gt f getRoomU getLocation I Associativity L to R quot208 Hillquot ujou I fgetRoomgetLocation is equivalent to fgetRoomgetLocation DormRoom f 39 num208 String String room 0 bldgName STACK T ESE112 ESE112 555112 More Interactions gt DormRoom rr gt Freshman f new Freshman Tomquot rr gt f getRoom getLocation Error Why I If you try to access a datafieldmethod of reference variable Whose value is null then you get a nullPointerException I ie you try to access some object that has not been created I Eg Person p pgetName Gives a runtime error I Runtime error because pgetName is valid syntax ie it compiles but does not execute Null in general I null is a legal value for any kind of reference variable I Example Person p Counter c Player mario p c and mario are null I null can be assigned tested and printed I Example ifmario null 555112 13 More Interactions II gt DormRoom room new DormRoom208 quotHillquot gt Freshman f new Freshmanquotjoquot room gt DOI IIIKDOIII r new uormRooml76 lcha1r gt fchangeRoomr In freshman class gt f39address 0 public String address quot176 MCNair ifr null return rgetLocation gt fhasARoom true else return no room 555112 11 Reference Variables as parameters DormRoom myRoom new DormRooml Hillquot f changeRoommyRoom voiu changeRoomwormRoom r room r l I When parameters of reference type are inputs the entire object is not copied Only the reference is copied This ryeans that myRoom and r refer to the same Jec I Changes made to the object referenced byr remain changed when the method returns I This is known as call by reference 555112 12 Introduction to Programming WI39fz Java for Beginners Process of Programming Fundamentals Comments amp Literals Operators Primitive Types amp Variables ExpressionsStatements Strings Process of Computer Programming I To come up with a computation solution Edit Syntax Semantics R t Compiletime un me i or or Syntax Error Semantic Error Run observe your output I Philosophy program in increments 555112 225 IDE I Use Integrated Development Environment I A software program that makes it easier to write compile and run programs I We re going to use the free Dr Java IDE I Setting up Dr Java on your personal PC I 39 iinnnn Ian hm EsE112 Comments I Comments are used to make code more understandable to humans I Java Compiler ignores comments this is a single line cement this is a multi line comment 555112 425 Literals I Literals are the values we write in a conventional form whose value is obvious 3 II An integer has no decimal point 105 Ila oating point double a Ila character has single quotes true II The boolean literals are oftwo types true false hello world II A string literal 555112 525 Arithmetic Operators I to indicate addition I to indicate subtraction I to indicate multiplication I to indicate division I to indicate remainder of a division integers only I parentheses to indicate the order in which to do things 555112 525 Relational Operators I equal to I not equal to I lt less than I gt greater than I lt less than equal to I gt greater than equal to I Note Arithmetic comparisons result in a Boolean value of true or false 555112 725 Boolean or Logical Operators I In English sentences conditions can be formed using quotandquot quotorquot and quotnotquot I Eg If there is a test and you did not study for it I In Java I H gt OR operator gt true if either operandquot is true I ampamp gt AND operator gt true only if both operands are true I gt NOT operator gts a unary operator applied to only one operand gt Reverses the truth value of its operand Operand a quantity upon which a mathematical operation is performed 555112 325 Expressions Operators Values 39 An expression has a value 39 An expression may consist of literals and operators 39 Given an expression DrJava prints its value Welcome to DrJava 3 gt 3 5 8 gt a A Equality operator false gt true ampamp false using the logical AND gt true false true using the logical OR Later we ll see that an expression may contain other things Such as variables method calls 555112 925 Values Types and Expression I Value Piece of data 23 105 true a I Type Kind of data integer floating point boolean truefalse character I An expression has a value or rather evaluates to a value 23 gt 23 10520 gt 125 3 5 6 gt 33 gt Precedence Order 2 3415 gt 0 gtWhyzero true ampamp false gt false 555112 1025 Types 0 very important concept I All data values in Java have a type I The type of a value determines I How the value is stored in memory I What operations make sense for the value I How the value can be cast converted to related values I Note Types are very helpful in catching programming errors 555112 1125 Primitive types Values that Java knows how to operate on directly We will work with 4 of Java s 8 primitive types I lntegerint 1 42 I Fractional floating point number double 5 2 99792458E8 I Character char 1J1 1 my I Truth value boolean true false Java s othertypes are byte short long float 555112 1225 Storage Space for Numerics I Numeric types in Java are characterized by their size how much memory they occupy I lntegertypes type I size I range char 2 bytes I065535 int 4 bytes I21474836482147483647 I Floating point types 49E324 double Bbytes 17E308 555112 1325 Another Important Type String I A String is an Object not a primitive type I Java also has objects cover objects later I String is composed of zero or more chars I A String is a sequence of characters enclosed by double quotes quotJavaquot quot3 Stoogesquot quotIiIJl I means concatenation for strings Variables I A variable is a named place in memory used to store a value I Variable must always be associated with type I It tells the computer how much space to reserve for the variable I The value stored can vary over time 555112 1525 quot3quot quot quot quotStoogesquot 3 Stoogesquot I Automatic conversion of numbers to strings 3 quot quot quotStoogesquot 3 Stoogesquot ESE112 14l25 Identifiers I Identifiers are names that you as a coder make up I Variable names I Also class and method names next topic to cover I Variable names I Java Rule May consist of alphanumeric characters and the underscore and must start with a letter I Style Rule Should be a noun that starts with an lowercase letter I Eg sum average I If the name has multiple words capitalize the start of every word except the first style rule I Eg firstName lastName 555112 1525 Declaring variables I All variables must be declared before being used I With a declaration statement I Declaration statement I Specifies the type of the variable followed by descriptive variable name followed by semicolon I Examples int seats double averageHeight boolean isE riday String houseName 555112 1725 Storing value into Variables I To store values into variable we use the assignment operator Ie I Variable Expression gt assignment statement I Important I Assignment statement must end with a semicolon I When a variable is assigned a value the old value is discarded and totally forgotten I Examples seats 150 averageHeight 21 174 1583 isE ri ay true houseName quotgryffindorquot 555112 1325 Variable value and type I The value of a variable may be changed x 57 I However its type may not x true this causes an error compiler will complain 555112 1925 Initializing Variables I It s good idea to declare and initialize a variable in one statement double milesPerHour 605 String mme quotDiana Palsetiaquot 555112 2025 Constants I Variables that don t change I Once the program in compiled they do not change overthe execution of the program I Rules I Java Rule Must have the keyword nal before the W79 I Style Rule Should have all caps for variable name final int NORTH 0 final int MILESPERGALLON 32 555112 2125 Integer Division I gt 10 I 3 3 I gt double10 l 3 10 is cast to a double 33333333333333335 I gt 10 I double 3 ll 3 is cast to a double 33333333333333335 I gt double10l3 ll 103 is cast to a double 30 lnteger division truncates 555112 2225 Examples of String creation gt String s2 quothelloquot gt s2 quot youquot quothello youquot gt s2 quotThe result is quot 100 gt s2 quotThe result is 100quot 555112 2525 Systemoutprintnstring I Command that prints string to the output screen I Can also print literals and expression values I The answer is automatically converted to string I Prints every time on a new line I Useful in finding semantic errors in a program Systemoutprintln hello worldquot System out println x Systemoutprint x x 555112 2425 Recap I An Expression I Has a value I Consists literals and operators FOR NOW I A Statement declaration and assignment I Must end with semicolon I Tells or commands the computerto do something I Comments are ignored by the computer I They are explanations of your program for human beings to rea 555112 2525 Introduction to Programming with Ja Va for Beginners List Collections I Data Groups of entities of similar kind I CD collection I Items in store I Characters in a video game I Methods Do the same thing to all of them I Computing the total number of tracks I Adding sales tax to all the prices I Moving all of them one step forward Array Recap I Kind of a collection yersnnn penple PM E penple new PersunI mm aquot 71 Duquot lair penple new Persn n penple1new Persun f1 94ml m liseleuza nun Problems with Arrays I Figtlted size I Optimal size may depend on information unavailable at creation time I Not good with dynamic growth I Cannot add and remove elements without the pain of resizing I A collection that can dynamically resize is known as a is Lists I Basic requirements I Add an element I Perform an operation on all elements I We will look at I How to create a typespeci c List for PointsStrings I A much more convenient List the one provided in the API that works on any type Visualizing a list I A sequence of references to objects of a given type I Indexed by 0 1 2 I A list of Points A TypeSpeci c List for Points lic hanlean addPnint p Add pm me he R elumslalse w duplicates are nut permitted and already cunlams me speemeu element public hanlean remnve nint p R emuve the list uccunence Ulp elums uue Willis cullecliun eumameu the speemeu element public hanlean cantains nint p Teslwnelnevlne list cunlamsp public int sizeo Number ulelemenls in list public Paint getint i ceme m eiemem ume m slanslmm u u lt 1 u i lt men public vcia setint i Paint p Selme im elemenllu b ultimiltszeu Using a typespeci c List PointList points new pointListo pointsa new Point1020 pointsaddnew Point3040 pointsaddnew Point5060 gt pointssize 3 gt gt gt gt gt pointsget2 getx 50 Now a list of Strings public boolean addstring s Add 5 to the list public boolean removestring s Remove the rst occurrence of 5 public boolean containsstring s Test whether the list contains 5 public int size Number of elements in list public String getint i Get the ith element of the list starts from 0 0 lt i ampamp i lt size public void setint i String s Set the ith element to s 0 lt i ampamp i lt size Problems Code Duplication Lack of abstraction Much of the functionality of a list doesn t depend on the element type Eg2 size add remove swap etc public void swapPointList list int i int j P in p listgeti listseti listgetj listsetj p public void swapStringList list int i int j 39 g s listgeti listseti listgetj listsetj s The javautiList interface 39 The Java APl s List interface works with any Object public interface List public int size public boolean isEmpty public boolean addObject element public void addint i Object element public Object get int i public Object remove int i public boolean containsObject e public Object set int i Object element Cannot do List myList new List ArrayList 39 ArrayList is a concrete classes 39 Implements the List interface 39 Does dynamic resizing for you 39 Typical Usage 39 Use List for variables and parameters 39 Use ArrayList when instantiating the list List chracks new ArrayList Typical Usage of List interface I Example ArrayList with Strings gt import javautil gt f1 words new gt wor s addquotcatquot gt words addquotratquot gt words get 1 quotratquot 39One approach for processing all items in a List for int i 01 lt words size i Systemout println Object Type words get i Some more problems I Use of the type Object as the basic type for objects that are stored in a list leads I Need to use typecasting in almost every case when an element is retrieved from that list I Since any type of object can legally be added to the list there is no way forthe compilerto detect an attempt to add the wrong type of object to the list The error will be detected only at run time ie when the object is retrieved from the list and the attempt to typecast the object fails Solution Parameterized Types I An array of type BaseType can only hold objects of type BaseType I An attempt to store an object of the wrong type in the array will be detected by the compiler I There is no need to typecast items that are retrieved from the array back to type BaseType I Instead of using the plain quotListquot type it is possible to use Listlt BaseTypegt I Where BaseType is any object type that is the name of a class or of an inte ace I BaseType cannot be one of the primitive types I Used to create lists that can hold only objects of type ample ListltPointgt p1 new ArrayListltPointgt ArrayListltPointgt p2 new ArrayListltPointgt0 Introduction to Programming WI39fz Java for Beginners API Random Class Math Class Dynamic vs Static Java Library I Java provides a huge library or collection of useful programs I A gold mine of welltested code that can save you countless hours of development time I This huge library information is provided in API Application Programming Interface EsE112 Using Library API I We will use API documentation for Java Version 5 I With the help of Javadocs we can use already implemented code I Find the documentation forthe Random class I Ifyou scroll down the lower left panel and click on the link labeled Random the large quotmainquot panel on the right will display the documentation forthe Random class EsE112 Random Class I A class to create Random numbers I Constructor Summary shows the objects of this type can be created I Eg Random r new Random I Method Summary shows that it can generate random values of types I integers doubles etc I Eg rnextlnt6 Generate a integer numbers between 0 inclusive and 6 exclusive I How do I generate a number between 1 and 6 2 EsE112 Packages and import Statements I What is a package I Basically it39s a directory that has a collection of related classes I Eg Random Class description containsjavautilRandom I Indicating that the Random class code is stored in the directory pa javautil somewhere on your machine quotutilquot or utility package I Inorder to use implemented work need to tell Java compiler where class is located I Use import statement importjavautilRandom Another way is to use the asterisk quotwildcard characterquot import javautilf EsE112 Math Class I Math Class Interface Field Summary Has two constants PI and E Constructor Summary has no public constructor Methods Summary many methods all which are static Method Details eg sqrt takes a double and returns a double EsE112 Math Class Description I Notice the phrase javalang at the top ofthe main panel above the word Math I This means that the Math class is part of the core Java language and hence can be used directly No need ofan import statement gt MathPl 3141592653589793 gt Math E 2718281828459045 gt Mathsqrt25 gtIMathpow210 gt Mathcos0 gtIMathcos2 MathPl ESE112 How the Math Class is Implemented public class Mathl public static final double PI 3141592653589793 public static double sin double d public static double sqrtdouble d l l gt MathPI 3 141592653589793 gt Math sqrt 25 50 EsE112 What39s different about Math Class I It s different from OOP class I It is a stateless class I We only need one Math class Notmultiple instances I No need to instantiate it Hence no public constructor I All of its variables and methods are static static means applies to the class as a whole vs applies to an individual instance EsE112 Dynamic Variables and Methods I All instance variables object data and methods object ehavior created without static keyword I Note There is no dynamic keyword in Java I Dynamic by default I In general dynamic refers to things created at run time ie when the program is running I Every object gets its own dynamic instance variables I Every object effectiver gets its own copy of each dynamic metho EsE112 Example Ticket public class Tickett private static int num39l icketssold o shared private int ticketnum one per object public TicketO num39l icketssold num39l icketssold l ticketnum nuln39l icketssold public static int getnumbersoldo return num39ricketssold public int get39l icket umbero return ticketnum public string getln o return t39cket it 39v ticketnum quot quot num39l icketssold quot tickets soldquot EsE112 Static Variables with 00 class I Static means pertaining to the class in generalquot notto an individual object I Variable is declared with the static keyword outside all methods I Eg static int numTicketsSold39 There is one variable numTickets for the class not one per object I A static variable is shared by all instances if any I All instances may be able readwrite it EsE112 Static Methods with 00 class I A method may be declared with the static keyword I Static methods live at class level not at object level I Static methods can access static variables and methods but not dynamic ones I How could it choose which one We have not created any objects ye I Example public static int getNumSold return numTicketsSold EsE112 Static Variables amp Methods in General I A static method that is public can be accessed I ClassNamemethodNameargs I double result Mathsqrt250 I int sold TicketgetNumberSold I boolean b isHappy10 I A static variable that is public may be accessed I Using ClassNamevarableName Eg MathPI MathE I Static variables act as global variable ie accessible within any static method EsE112 Ticket class Interactions gt Ticketget umbersold 0 gt Ticket t1 new Ticketo gt t1getTicket ullI 1 gt t1getInfo quotticket it 1 1 ticket s soldquot gt t1getllumbersold 1 gt Ticket t2 new Ticketo gt t2getTicket ullI 2 gt t2getInfo quotticket it 2 2 ticket s soldquot gt t1getInfo quotticket it 1 2 ticket s soldquot gt Ticketgetllullbersold 2 EsE112 Main method is static I To have standalone Java Application we need a method public static void mainString args I The main method belongs to the class in which it is written I Hence it is static ie does not belong to any object I Note Instance variable cannot be referenced from main unless the object is created EsE112 Example public class Point X int y public static void mainString args x y 10 all are wrong EsE112 Solution public class Point lnt public void setXint val X 5 public static void mainString args Point p new Po39nt psetX5 Remember that if no constructor is written java creates a default constructor and initializes the instance variables to their default values EsE112 When to use static with OOP I A variable should be static if I It logically describes the class as a whole I There should be only one copy of it I A method should be static if I It does not use or affect the object that receives the message it uses only its parameters EsE112 Static amp Dynamic Rules Recap static variables and methods belong to the class in general not to individual objects The absence of the keyword static before nonlocal variables and methods means dynamic one per object nstance A dynamic method can access all dynamic and static variables and methods in the same class A static method can not access a dynamic variable How could it choose or which one A static method can not call a dynamic method because dynamic method might access an instance variable EsE112
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'