• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Variables methods and_objects_lecture_2
 

Variables methods and_objects_lecture_2

on

  • 213 views

 

Statistics

Views

Total Views
213
Views on SlideShare
213
Embed Views
0

Actions

Likes
0
Downloads
5
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Variables methods and_objects_lecture_2 Variables methods and_objects_lecture_2 Presentation Transcript

    • Copyright © 2000-2002 Tom Hunter
    • Copyright © 2000-2002 Tom HunterIn Java there are three kinds of variables.The difference has to do with scope.Java Basics2
    • Copyright © 2000-2002 Tom HunterThe Three Are:Class VariablesInstance VariablesLocal VariablesJava Basics3
    • Copyright © 2000-2002 Tom HunterThe Three Are:Class Variables--declared with ‘static’Instance Variables--declared outside of any methodLocal Variables--declared inside of a methodJava Basics4
    • Copyright © 2000-2002 Tom HunterLocal Variables
    • Copyright © 2000-2002 Tom HunterLocal VariablesWhen you declare a variable inside a method, it isa local variable.It lives only as long as the method lives.We say it has ‘method scope’.Java Basics6
    • Copyright © 2000-2002 Tom Hunterpublic class ShowLocalVariables{public void aMethod(){int x = 0;StringBuffer d = new StringBuffer( “myBuffer”);}}‘x’ and ‘d’ are declared within themethod. Since they are declared withinthe method, they have ‘method scope’and they live only as long as the methodis alive.7
    • Copyright © 2000-2002 Tom Hunterpublic class ShowLocalVariables{public void aMethod(){int x = 0;StringBuffer d = new StringBuffer( “myBuffer”);}}Notice that I have not included an‘access modifier’ such as public,private or protected. Why?Because all local variables areautomatically private.In fact, it is a syntax error toinclude an access modifier on a localvariable and the compiler will complainloudly.8
    • Copyright © 2000-2002 Tom Hunterpublic class ShowLocalVariables{public void aMethod(){int x = 0;StringBuffer d = new StringBuffer( “myBuffer” );}}Also notice that I have initialized theprimitive variable ‘x’ to zero, and I haveinstantiated the object variable ‘d’.A local variable must always bemanually set to an initial value.9
    • Copyright © 2000-2002 Tom HunterInstance Variables
    • Copyright © 2000-2002 Tom HunterInstance VariablesWhen you declare a variable outside any method, itis an instance variable.It lives only as long as the instance of this classlives.We say it has ‘instance scope’.Java Basics11
    • Copyright © 2000-2002 Tom HunterInstance VariablesAn instance variable will be automaticallyinitialized.Primitive numeric variables will automatically beinitialized to zero.Object variables will be automatically initialized tonull.Strings will be set to spaces.Java Basics12
    • Copyright © 2000-2002 Tom HunterInstance VariablesTake close notice of the word ‘instance’.When you have an instance variable, each instanceof the class gets its own set of the instancevariables in a class.Java Basics13
    • Copyright © 2000-2002 Tom Hunterpublic class InstanceVariables{private int x;private StringBuffer d;public void aMethod(){d = new StringBuffer( “myBuffer” );}}Notice I have declared‘x’ and ‘d’ outside ofany method.Even though I’minstantiating ‘d’ in amethod, it will live andhold its value beyondthis method’s life.14
    • Copyright © 2000-2002 Tom Hunterpublic class InstanceVariables{private int x;private StringBuffer d;public InstanceVariables( int p, StringBuffer w ){x = p;d = w;}public String toString(){String out = “x=“ + x + “,d=“ d.toString();return out;}}In a moment we will make aninstance of this class, but firsta question:15
    • Copyright © 2000-2002 Tom Hunterpublic class InstanceVariables{private int x;private StringBuffer d;public InstanceVariables( int p, StringBuffer w ){this.x = p;this.d = w;}public String toString(){String out = “x=“ + x + “,d=“ d.toString();return out;}} Is it legal to use the ‘this’ reference above?16
    • Copyright © 2000-2002 Tom Hunterpublic class InstanceVariables{private int x;private StringBuffer d;public InstanceVariables( int p, StringBuffer w ){this.x = p;this.d = w;}public String toString(){String out = “x=“ + x + “,d=“ + d.toString();return out;}}Yes! This line says: “Take the value of ‘p’ and assign itto the instance variable ‘x’ in thisthis instance.”17
    • Copyright © 2000-2002 Tom Hunterpublic class Tester{public Tester(){InstanceVariables v;v = new InstanceVariables( 5, “hello” );System.out.println( v.toString() );}public static void main( String[] args ){Tester t = new Tester();}}Let’s follow the sequence of execution here.x=5,d=hello18
    • Copyright © 2000-2002 Tom Hunterpublic class Tester{public Tester(){InstanceVariables a, b, c;a = new InstanceVariables( 5, “hello” );b = new InstanceVariables( 6, “howdy” );c = new InstanceVariables( 7, “hi” );System.out.println( a.toString() );System.out.println( b.toString() );System.out.println( c.toString() );}public static void main( String[] args ){Tester t = new Tester();}}Now, we will create multiple instances. The key point? Eachinstance of the class has its own copyown copy of those variables.x=5,d=hellox=6,d=howdyx=7,d=hi19
    • Copyright © 2000-2002 Tom HunterClass Variables20
    • Copyright © 2000-2002 Tom HunterstaticA ‘class variable’ is declared with thekeyword ‘static’.‘static’ variables belong to the class,not to any one instance of the class.When you declare a variable as static,then all instances of the class shareshare one copyof that variable.Java Basics21
    • Copyright © 2000-2002 Tom HunterstaticAs soon as the class is loaded--andbefore you have even instantiated aninstance of the class (with the new keyword),you can access a static variable.This fact governs static variables andtheir behavior.Java Basics22
    • Copyright © 2000-2002 Tom HunterstaticSay you had a class calledSavingsAccount, which held theinformation for a single person’s account.Our bank has a million instances of thisclass to serve our million customers.Java Basics23
    • Copyright © 2000-2002 Tom HunterstaticIf--by mistake--this class containedan instanceinstance variable called ‘interestRate’,then--every time the interest rate changed--you’d have to go out and update a millioninstances with the new interest rate.But, if you made the variable static,then all instances share one copy. Change itonce and you’ve updated it for everybody.Java Basics24
    • Copyright © 2000-2002 Tom Hunterstaticstatics are snobs. They onlyassociate with their own kind.If you have a static variable, then it canonly be accessed by a method that has beendeclared as static.Java Basics25
    • Copyright © 2000-2002 Tom HunterstaticThat makes sense.Since a static variable can exist evenwhen there isn’t an instance of the class, thena static method would exist even when thereisn’t an instance.Java Basics26
    • Copyright © 2000-2002 Tom HunterstaticTo access a static variable, you need astatic method.A static method can only call anotheranotherstatic method--because that’s the only kind ofmethod that’s sure to be present, even if wedon’t have an instance of the class.Java Basics27
    • Copyright © 2000-2002 Tom Hunterpublic class SnobbyStatics{static double interest;public static double getInterest(){return interest;}public static void setInterest( double inter ){interest = inter;}} 28
    • Copyright © 2000-2002 Tom Hunterpublic class SnobbyStatics{static double interest;public static double getInterest(){return interest;}public static void setInterest( double inter ){this.interest = inter;}} 29For a static, is the ‘this’ keyword legal?The ‘this’ keyword means‘this instancethis instance’ and therefore itdoesn’t fit.
    • Copyright © 2000-2002 Tom Hunterpublic class SnobbyStatics{static double interest;public static double getInterest(){return interest;}public static void setInterest( double inter ){interest = inter;anotherStaticMethod();}public static void anotherStaticMethod(){System.out.println( “I’m ecstatic!” );}} 30Does this make sense?Can you call a static method fromwithin another static method?
    • Copyright © 2000-2002 Tom Hunterpublic class SnobbyStatics{static double interest;public static double getInterest(){return interest;}public static void setInterest( double inter ){interest = inter;}public double nonStaticMethodCallStaticMethod(){return getInterest();}} 31Is this legal? Having a non-staticmethod calling a static method?
    • Copyright © 2000-2002 Tom Hunter32public static double getInterest(){return interest;}public double nonStaticMethodCallStaticMethod(){return getInterest();}}Let’s understand why this is okay. Before we can call a non-static method, we would need to have an instance of the classinstantiated. At that point, will the static methods be available?Sure!Therefore, it is legal to call a static method from a non-static method.
    • Copyright © 2000-2002 Tom Hunterpublic class SnobbyStatics{static double interest;public static double getInterest(){return interest;}public static void setInterest( double inter ){interest = inter + aNonStaticMethod();}public double aNonStaticMethod(){return 0.0;}} 33Is this legal? Having a staticmethod calling a non-staticmethod?You can call a staticmethod without aninstance and the non-static method might notbe there.
    • Copyright © 2000-2002 Tom Hunter34static variable … used in a static method?static variable … used in a NON-static method?Non static variable … used in a static method?static method … called by another static method?static method … called by a Non static method?Non static method … called by a static method?
    • Copyright © 2000-2002 Tom Hunter35static variable … used in a static method? Of coursestatic variable … used in a NON-static method? NONon static variable … used in a static method? NOstatic method … called by another static method? YESstatic method … called by a Non static method? YESNon static method … called by a static method? NO
    • Copyright © 2000-2002 Tom Hunterstaticstatics are snobs. They onlyassociate with their own kind. If you have astatic variable, then it can only be accessedby a method that has been declared as static.That makes sense. Since a static canexist even when there isn’t an instance of theclass, then a static method would exist evenwhen there isn’t an instance.Java Basics36
    • Copyright © 2000-2002 Tom HunterJava MethodsPass by Value
    • Copyright © 2000-2002 Tom HunterIn Java, when you call a method, a copy ofthe argument is always passed.Because it passes a copy, the original cannever be changed.Ah! But don’t let that fool you.Java Methods, Pass by Value38
    • Copyright © 2000-2002 Tom HunterWhen you’re dealing with a primitivevariable, that is literally true.Java makes a duplicate of the originalvariable and makes an exact copy of thecontents of the variable.Java Methods, Pass by Value39
    • Copyright © 2000-2002 Tom Hunterpublic class PassByValueMysteries{private int x = 59;public PassByValueMysteries(){System.out.println( “Before x=“ + x );tryToChangeMyArgument( x );System.out.println( “After x=“ + x );}public void tryToChangeMyArgument( int q ){q++;}public static void main( String[] args ){PassByValueMysteries m = new PassByValueMysteries();}}x 59q 59q 60Before x=59After x=5940
    • Copyright © 2000-2002 Tom Hunterpublic class PassByValueMysteries{private StringBuffer x;public PassByValueMysteries(){x = new StringBuffer( “before” );System.out.println( “Before x=“ + x.toString() );canChangeMyArgument( x );System.out.println( “After x=“ + x.toString() );}public void canChangeMyArgument( StringBuffer q ){q.append( “ after” );}public static void main( String[] args ){PassByValueMysteries m = new PassByValueMysteries();}}Xq 1221231314Before x=beforeAfter x=before after1221231314beforeX 12212313141221231314before after41
    • Copyright © 2000-2002 Tom HunterSo, you see the principle is consistent.The twist is this: a reference contains aadifferent kind of datadifferent kind of data--the address of theobject. So, if we send the address of theoriginal object (as the data contained in thevariable we’re sending) then we can changethe original.Java Methods, Pass by Value42
    • Copyright © 2000-2002 Tom HunterWhat Really HappensWhen You InstantiateAn Object
    • Copyright © 2000-2002 Tom HunterNext, I will show you a simple class, and Iwant you to tell me what the sequence isWhat Really Happens When You Instantiate An Object44
    • Copyright © 2000-2002 Tom Hunterpublic class Test{public Test(){Bbb b = new Bbb();}public static void main(String[] args){Test t = new Test();}}public class Object{public Object(){System.out.println( “Object Const” );}}public class Aaa{public Aaa(){System.out.println( “Aaa Const” );}}public class Bbb extends Aaa{public Bbb(){System.out.println( “Bbb Const” );}}Test mainTest constObject ConstAaa ConstBbb Const45
    • Copyright © 2000-2002 Tom HunterQuestions?Requests for futuretopics?