1 the “Static” Keyword

Total Page:16

File Type:pdf, Size:1020Kb

1 the “Static” Keyword The Plan • The static Keyword • Wrapper classes • Object interaction Lecture 2 Java Intermediate • Inheritance Dr. Tommy Yuan Java Refresher Java Refresher 1 2 The “static” Keyword • The data in a class may exhibit different scopes, e.g. – shared amongst all instances of that class - class variable – local to that object instance - instance variable The “static” Keyword Shared Class A static attributes and static methods Object A1 Object A2 Object A3 Object A4 Local A1 Local A2 Local A3 Local A4 Java Refresher Java Refresher 3 4 Class Attributes – The static Keyword Class Methods – The static Keyword Class exercise:What do we get? A better design public void testBankAccount() class BankAccount public void testBankAccount() class BankAccount { { { { //Create two bank accounts // the attributes //Create two bank accounts // the attributes BankAccount account1 = new private String accountNumber; BankAccount account1 = new private String accountNumber; BankAccount(); private String accountName; BankAccount(); private String accountName; BankAccount account2 = new private double balance; BankAccount account2 = new private double balance; BankAccount(); private static double interestRate; BankAccount(); private static double interestRate; //Deposit some money // the methods //Deposit some money // the methods account1.deposit(1000); public void setInterestRate(double rateIn) account1.deposit(1000); public static void setInterestRate(double rateIn) account2.deposit(2000); { account2.deposit(2000); { //Set the interest rate interestRate = rateIn; //Set the interest rate interestRate = rateIn; account1.setInterestRate(10); } BankAccount.setInterestRate(10); } account2.setInterestRate(20); public void addInterest() BankAccount.setInterestRate(20); public void addInterest() //Add interest to account1 and display { //Add interest to account1 and display { account1.addInterest(); balance = balance account1.addInterest(); balance = balance System.out.println(account1.getBalance()); + (balance *interestRate)/100; System.out.println(account1.getBalance()); + (balance *interestRate)/100; … } … } } … Java Refresher } … Java Refresher } } 5 6 1 Class Methods – The static Keyword JOptionPane – Another Example of Static Methods • We want to use the services of a class (i.e. call a • Earlier we have seen the use of the Scanner class method), without having to create an object. in handling terminal input/output • Here are some examples you may recognize. • The javax.swing.OptionPane class provides – System.out.println(“ ….”); prepackaged Graphical User Interface dialog – Math.sqrt(x); boxes to get information from users and display – Math.random(); messages – showInputDialog(..) – showMessageDialog(..) Java Refresher Java Refresher 7 8 JOptionPane – Another Example of Static Methods 1/2 JOptionPane – Another Example of Static Methods 2/2 import javax.swing.JOptionPane; public class GUI_IO { public void basicPromptDisplay() • There is a problem …. The showInputDialog() { String name = JOptionPane.showInputDialog("What is your name"); method will ONLY return strings. Therefore how JOptionPane.showMessageDialog(null, can we use this GUI box to input other data (int, "Hi " + name + " how do you like these dialog boxes?", doubles…) "A Question", JOptionPane.QUESTION_MESSAGE ); } • Answer …Wrapper classes public static void main(String args[]) { GUI_IO gui=new GUI_IO(); gui.basicPromptDisplay(); } } Java Refresher Java Refresher 9 10 Wrapper Classes Wrapper Classes • Autoboxing Object o=37; Primitive Class • Wrap around the basic type, and add some very int Integer • Unboxing Integer io=(Integer)o; useful methods to it. int x=io; double Double • For example, those • The following example shows how to convert a string to an integers by using the parseInt(s) method: which allow conversion float Float from one type to another- e.g. strings to numbers and vice-versa. char Character • In the java.lang package … … Java Refresher Java Refresher 11 12 2 Object Interaction . Much of the power of Object Oriented programming lies in the ability for objects to interact with one another to deliver the overall functionality. Need to know who to interact Object Interaction . Closely related concept is class association . Self interaction . One-way interaction . Two-way interaction Java Refresher Java Refresher 13 14 Object Interaction Object Interaction . Self interaction . One way interaction . Association via public class Student { parameter public double consumeDrink(Drink drink) public class Circle { { alcohol += drink.getLitres() * … drink.getProof(); public void changeColor() return alcohol; { } color = newColor; draw(); Public class Drink } { private void draw() public double getLitres(){…} {…} public String getProof(){…} } } Java Refresher Java Refresher 15 16 Object Interaction Object Interaction . One way interaction, 0..1 . Composition (whole part relation) . Association via attribute Patient Consultant . Aggregation-weaker notation public class ClockDisplay { public class Patient { // declare two references to NumberDisplay objects private Consultant assignedConsultant; private NumberDisplay hours; //Methods for assign and unassign consultant private NumberDisplay minutes; … private String displayString; // simulates the actual display public String getConsultant() { // Constructor to create a new clock set at the time specified by String conDetails; the parameters. conDetails = "\nConsultant Name = "+assignedConsultant.getName(); public ClockDisplay(int hour, int minute) return conDetails; { hours = new NumberDisplay(24); } minutes = new NumberDisplay(60); setTime(hour, minute); Java Refresher } Java Refresher 17 18 3 Object Interaction . Two-way interaction View { Control c =new Control (this); View Control doit(){c.m();} display(…){…} } Control Inheritance In Java { View v; Control (View v) { this.v=v; } m(){v.display(…);} } Java Refresher Java Refresher 19 20 Inheritance In Our Life Single Inheritance In Java . Inherits all the Sub(){super(); attributes and ...} . In Biology methods except Double inheritance . constructor …… . method overriding . Inherits the type . The subclass Shape s=new Triangle(); specialises . In Law The child may not accept it …. Java Refresher Java Refresher 21 22 Single Inheritance In Java Single Inheritance In Java public class Shape{ . Concrete Shape . Abstract Animal class public abstract class Animal{ ... class abstract public void run(…); } . At least one abstract method } . Not permitted to create instances public class Circle public class Rectangle extends Shape{ extends Shape{ ... ... Each concrete class public class Tortoise extends } } should implement all Animal{ inherited abstract public void run(…){…} methods } keyword keyword Java Refresher Java Refresher 23 24 4 Single Inheritance In Java Key Benefits 1. Parent class reuse . Actor interface public interface Actor{ . All methods are abstract though void run(…); Code reuse and duplication avoidance abstract keyword is not needed boolean active(); 2. Type conformance } . Not permitted to create instances Increasing flexibility through polymorphic variables and . All methods are public though public dynamic binding keyword is not needed . All attributes are final, public and Shape s1 = area() keyword static new Circle(20,30,50); Shape s2 = new Triangle(); Shape s3 = new Rectangle(); public class Tortoise . Each concrete class should implements Actor{ implement all inherited methods ... } Received the same message, but react differently What are the issues with dynamic binding? Java Refresher Java Refresher 25 26 Multiple Inheritance Multiple Inheritance Having a class inherit directly from multiple ancestors . Key problem Ambiguities e.g. the diamond problem D d=new D(); d.m1(); Does Java support multiple inheritance? Which method should do the job? Cause: inherited code from several places (classes) Java Refresher Java Refresher 27 28 Multiple Inheritance In Java What do we actually gain by implementing interfaces? . Java forbids it for classes 1. Multiple parent class reuse . Java permits it for interfaces class D extends A, B{} – No competing implementation . Extends at most one class, and/or 2. Multiple type conformance implements one or A a=new D(); more interfaces B b=new D(); class D implements A, B {} Java Refresher Java Refresher 29 30 5 Is Java good enough? Is Java good enough? From Java Designer Joseph says (Gosling and McGilton 1996 pp29) (Bergin J. 2000 ) “ Multiple inheritance - and all the problems it “…Java is a good, sound, and complete generates - was discarded from Java. The language design that supports the kinds of desirable features of multiple inheritance are things that developers need. It takes skill, provided by interfaces” however, to see how to achieve some of the less used idioms such as multiple inheritance.” Convinced? How? Java Refresher Java Refresher 31 32 Interface-delegation Technique Interface-delegation Technique Aims: 1. A StudentTeacher wants to become a Teacher 2. A StudentTeacher wants to be able to grade [reuse grade()] Step 2: Teacher talks to StudentTeacher: Now, you can become Step 1: Separate Teacher class a Teacher. Go for it. Java Refresher Java Refresher 33 34 Interface-delegation Technique Interface-delegation Technique Step 3: StudentTeacher: I am a teacher now, but I don’t know how to grade [reuse grade()] yet? All done! Teacher: Ask my delegate TeacherImpl to do it for Delegation takes place you, she knows how to do it. Java Refresher Java Refresher 35 36 6 Interface-delegation Technique Interface-delegation
Recommended publications
  • 18-Variables.Pdf
    Mehran Sahami Handout #18 CS 106A October 12, 2007 Variables, variables, everywhere… Based on a handout by Patrick Young. Local Variables Local variables are created local to the method (or the block—see “Block Scope” section below) in which they are defined. They are destroyed when execution of the method has been completed. Local variables can only be accessed from within the method in which they are declared. Because of their transient nature, local variables cannot store persistent information about an object between method calls. Local Variables Example Consider, for example, the following snippet of code. class AnExample extends ConsoleProgram { public void methodOne { int a = readInt("Enter a: "); println("a = " + a); } public void methodTwo { int b = a; // BUG!: cannot refer to variable a in methodOne println("b = " + b); } } The variables a and b are local variables declared within different methods in the class AnExample . Because these variables are local variables, a can only be referred to within methodOne and variable b can only be accessed within methodTwo . Our attempt to initialize b using the value of a is illegal, as code in methodTwo cannot access local variables from methodOne or any other method. Because local variable values do not persist after their containing method has completed, the variable a will be destroyed when methodOne has completed execution. The next time methodOne is called, a new variable a will be created. Block Scope While we typically think of local variables as local to a particular method, in Java local variables are actually local to a block of code. While a method defines a block of code (since the opening and closing braces of the method define a block), for and while loops, if -statements, and other constructs are also considered blocks of code.
    [Show full text]
  • Chapter 5 Names, Bindings, and Scopes
    Chapter 5 Names, Bindings, and Scopes 5.1 Introduction 198 5.2 Names 199 5.3 Variables 200 5.4 The Concept of Binding 203 5.5 Scope 211 5.6 Scope and Lifetime 222 5.7 Referencing Environments 223 5.8 Named Constants 224 Summary • Review Questions • Problem Set • Programming Exercises 227 CMPS401 Class Notes (Chap05) Page 1 / 20 Dr. Kuo-pao Yang Chapter 5 Names, Bindings, and Scopes 5.1 Introduction 198 Imperative languages are abstractions of von Neumann architecture – Memory: stores both instructions and data – Processor: provides operations for modifying the contents of memory Variables are characterized by a collection of properties or attributes – The most important of which is type, a fundamental concept in programming languages – To design a type, must consider scope, lifetime, type checking, initialization, and type compatibility 5.2 Names 199 5.2.1 Design issues The following are the primary design issues for names: – Maximum length? – Are names case sensitive? – Are special words reserved words or keywords? 5.2.2 Name Forms A name is a string of characters used to identify some entity in a program. Length – If too short, they cannot be connotative – Language examples: . FORTRAN I: maximum 6 . COBOL: maximum 30 . C99: no limit but only the first 63 are significant; also, external names are limited to a maximum of 31 . C# and Java: no limit, and all characters are significant . C++: no limit, but implementers often impose a length limitation because they do not want the symbol table in which identifiers are stored during compilation to be too large and also to simplify the maintenance of that table.
    [Show full text]
  • Java Static Keyword
    This page was exported from - TechnicalStack Export date: Sun Sep 26 13:56:23 2021 / +0000 GMT Java static keyword Java static keyword The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class. The static can be: - variable (also known as class variable) - method (also known as class method) - block - nested class 1) Java static variable If you declare any variable as static, it is known static variable. - The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc. - The static variable gets memory only once in class area at the time of class loading. Advantage of static variable It makes your program memory efficient (i.e it saves memory). Understanding problem without static variable class Student{ int rollno; String name; String college="ITS"; } Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once. Java static property is shared to all objects. Example of static variable //Program of static variable class Student8{ int rollno; String name; static String college ="ITS"; Student8(int r,String n){
    [Show full text]
  • CS 61A A&S Section 3.0 Object-Oriented Programming
    CS 61A A&S Section 3.0 Object-Oriented Programming | Above the line view This document should be read before Section 3.1 of the text. A second document, \Object-Oriented Programming | Below the line view," should be read after Section 3.1 and perhaps after Section 3.2; the idea is that you first learn how to use the object-oriented programming facility, then you learn how it's implemented. Object-oriented programming is a metaphor. It expresses the idea of several independent agents inside the computer, instead of a single process manipulating various data. For example, the next programming project is an adventure game, in which several people, places, and things interact. We want to be able to say things like \Ask Fred to pick up the potstickers." (Fred is a person object, and the potstickers are a thing object.) Programmers who use the object metaphor have a special vocabulary to describe the components of an object-oriented programming (OOP) system. In the example just above, \Fred" is called an instance and the general category \person" is called a class. Programming languages that support OOP let the programmer talk directly in this vocabulary; for example, every OOP language has a “define class" command in some form. For this course, we have provided an extension to Scheme that supports OOP in the style of other OOP languages. Later we shall see how these new features are implemented using Scheme capabilities that you already understand. OOP is not magic; it's a way of thinking and speaking about the structure of a program.
    [Show full text]
  • Java Programming 2 – Lecture #1 – [email protected]
    Java Programming 2 – Lecture #1 – [email protected] About the Java Programming Language Java is an object-oriented, high-level programming language. It is a platform-neutral language, with a ‘write once run anywhere’ philosophy. This is supported by a virtual machine architecture called the Java Virtual Machine (JVM). Java source programs are compiled to JVM bytecode class files, which are converted to native machine code on platform-specific JVM instances. .java source .class JVM executable code files Java bytecode files JVM machine code compiler runtime Java is currently one of the top programming languages, according to most popularity metrics.1 Since its introduction in the late 1990s, it has rapidly grown in importance due to its familiar programming syntax (C-like), good support for modularity, relatively safe features (e.g. garbage collection) and comprehensive library support. Our First Java Program It is traditional to write a ‘hello world’ program as a first step in a new language: /** * a first example program to print Hello world */ public class Hello { public static void main(String [] args) { System.out.println(“Hello world”); } } Contrast with Python Whereas Python programs are concise, Java programs appear verbose in comparison. Python has dynamic typing, but Java uses static typing. Python scripts are generally interpreted from source, whereas Java programs are compiled to bytecode then executed in a high-performance just-in-time native compiler. 1 E.g. see http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html Supporting User Input in Simple Java Programs There are two ways to receive text-based user input in simple programs like our ‘hello world’ example.
    [Show full text]
  • Using the Java Bridge
    Using the Java Bridge In the worlds of Mac OS X, Yellow Box for Windows, and WebObjects programming, there are two languages in common use: Java and Objective-C. This document describes the Java bridge, a technology from Apple that makes communication between these two languages possible. The first section, ÒIntroduction,Ó gives a brief overview of the bridgeÕs capabilities. For a technical overview of the bridge, see ÒHow the Bridge WorksÓ (page 2). To learn how to expose your Objective-C code to Java, see ÒWrapping Objective-C FrameworksÓ (page 9). If you want to write Java code that references Objective-C classes, see ÒUsing Java-Wrapped Objective-C ClassesÓ (page 6). If you are writing Objective-C code that references Java classes, read ÒUsing Java from Objective-CÓ (page 5). Introduction The original OpenStep system developed by NeXT Software contained a number of object-oriented frameworks written in the Objective-C language. Most developers who used these frameworks wrote their code in Objective-C. In recent years, the number of developers writing Java code has increased dramatically. For the benefit of these programmers, Apple Computer has provided Java APIs for these frameworks: Foundation Kit, AppKit, WebObjects, and Enterprise Objects. They were made possible by using techniques described later in Introduction 1 Using the Java Bridge this document. You can use these same techniques to expose your own Objective-C frameworks to Java code. Java and Objective-C are both object-oriented languages, and they have enough similarities that communication between the two is possible. However, there are some differences between the two languages that you need to be aware of in order to use the bridge effectively.
    [Show full text]
  • 10. Classes: an Initial Example
    10. Classes: An Initial Example This is the first chapter about classes. It is also the first chapter in the first lecture about classes. Our basic coverage of classes runs until Chapter 13. 10.1. The Die Class Lecture 3 - slide 2 In this section we encounter a number of important OOP ideas, observations, and principles. We will very briefly preview many of these in a concrete way in the context of a simple initial class. Later we will discuss the ideas in depth. We use the example of a die , which is the singular form of "dice", see Program 10.1. One of the teaching assistants in 2006 argued that the class Die is a sad beginning of the story about classes. Well, it is maybe right. I think, however, that the concept of a die is a good initial example. So we will go for it! On purpose, we are concerned with use of either the singular or the plural forms of class names. The singular form is used when we wish to describe and program a single phenomenon/thing/object. The plural form is most often used for collections, to which we can add or delete (singular) objects. Notice that we can make multiple instances of a class, such as the Die class. In this way we can create a number of dice. The class Die in Program 10.1 is programmed in C#. We program a die such that each given die has a fixed maximum number of eyes, determined by the constant maxNumberOfEyes . The class encapsulates the instance variables : numberOfEyes , randomNumberSupplier , and the constant maxNumberOfEyes .
    [Show full text]
  • C++ Fundamentals
    C++ Fundamentals Only what you need to know Outline • Part 1 – Basic Syntax Review – C++ Definitions, Source Code Organization, Building your Code • Part 2 – Scope – Pointers and References – Dynamic Memory Allocation – Const-ness – Function Overloading • Part 3 – Type System – Brief Intro to Using Templates – C++ Data Structures – Standard Template Library Containers • Part 4 – Object Oriented Design – Classes in C++ 2 / 82 Typeface Conventions • Key concepts • Special attention required! • Code • // Comments • int x;// Language keywords 3 / 82 MOOSE Coding Standards • Capitalization –ClassName –methodName – member variable – local variable • FileNames – src/ClassName.C – include/ClassName.h • Spacing – Two spaces for each indentation level – Four spaces for initialization lists – Braces should occupy their own line – Spaces around all binary operators and declaration symbols + - * & ... • No Trailing Whitespace! • Documentation for each method (Doxygen keywords) – @param – @return – ///Doxygen Style Comment • See our wiki page for a comprehensive list https://hpcsc.inl.gov/moose/wiki/CodeStandards 4 / 82 Part 1 • Basic Syntax Review • C++ Definitions • Source Code Organization • Building your Code 5 / 82 Review: C Preprocessor Commands • “#” Should be the first character on the line – #include <iostream> – #include "myheader.h" – #define SOMEWORD value – #ifdef, #ifndef, #endif • Some predefined Macros – FILE – LINE – cplusplus 6 / 82 Review: Intrinsic Data Types Basic Type Variant(s) bool char unsigned int unsigned, long, short float double
    [Show full text]
  • Chapter 4 Methods
    Chapter 4 Methods Hello! Today we will focus on the static keyword, calling conventions of methods, and what scope and lifetime mean in Java. Now that our chapters will tend to generate multiple files, I strongly suggest you create a folder for each lab, and then just add files to that folder. Naming Things. Quick note on names: when we create a variable in a class – whether we make it static or not – we can refer to it as a field. We may refer to both fields and methods as members of the class. Although we have strived to use the same names for things, these words are commonly used to refer to the variables and methods in a class. Methods – Static Methods The way in Java to name a block of code, and then be able to call it elsewhere, is to write a method. A method always goes in a class definition. We have one major distinction to make, though: should the method be static or not? A static method can be called all by itself (no object of the enclosing class needed), much like a function in Python. A non-static method in Java is written in a class and associated with a particular object and thus can use the object's instance variables. Being non-static is the default behavior in Java, specified by the absence of the static modifier. We focus first in this tutorial on writing static methods. Non-static Method Example Here is an example of a non-static method, in the Square class: look at the perimeter method below.
    [Show full text]
  • Classes & Objects
    CLASSES AND OBJECTS Summer 2019 OBJECT BASICS • Everything in Java is part of a class • This includes all methods (functions) • Even the main() method is part of a class • Classes are declared similar to C++ • This includes the ability to categorize members as public or private, but the qualifiers are placed before each individual member • With no access level, a class member is considered package-private (accessible only to other classes in the same package, a concept discussed later) • These two categories have the same meaning as in C++: public means accessible from anywhere, private means only accessible from within the class • Follow the same guidelines as in C++ (member data usually private, member functions at an appropriate level based on access requirements) OBJECT BASICS • Class Declaration, continued • In Java, classes themselves have access levels. • Normal classes are usually declared public, so they can be accessed anywhere • Other access levels are usually reserved for specific types of classes (such as inner classes, discussed later) • Circle.java – class declaration example CREATING OBJECTS • Objects are created from a class using the new operator and they must be attached to a reference variable. This takes two steps: 1. Declare the object reference variable 2. Create the object with new and attach it to the reference variable • This means every object is dynamically created. CREATING OBJECTS • The Format: ClassName objectReference; objectReference = new ClassName(); OR ClassName objectReference = new ClassName(); • Examples:
    [Show full text]
  • Declaring Variables in Class Python
    Declaring Variables In Class Python Corky whinings her floorwalkers backstage, desiccated and ecaudate. Unchary Cy leverages falsely and creakily, she taunt her spermatocele vanned soulfully. Sigfrid remains plaintive: she rusticated her exclusivists jutted too respectfully? Global name an error and assign a derived class itself is that points describing the same way as a variable in python variables in class python. If to declare a class named Device and initialize a variable dev to plumbing new. The grab to porter this are nonlocal definitions, should be pleasure in the global namespace. This class contains a single constructor. It is faster and more add to attend the real Python course outside a classroom. Make sure your community account class, this allows multiple pieces of an interface, and how to take in class but the collection, known as spam! PHP because when are less structure than the traditional languages with your fancy features. Each tutorial at Real Python is created by a soft of developers so leaving it meets our incredible quality standards. Object Oriented Programming in Python Stack Abuse. The special function are not create an input data type object oriented programming languages often think of m_value: if we are. Python class Objects and classes Python Tutorial Pythonspot. Objects can be a double underscores when you define what are in order for. Understanding Class and Instance Variables in Python 3. For example also it in which makes up! Instances of a Class Python Like root Mean It. This stage notice provides an overturn of our commitment to privacy and describes how we color, and undo some applications that might achieve a real choice.
    [Show full text]
  • A Uniform Model for Object-Oriented Languages Using the Class Abstraction
    A Uniform Model for Object-Oriented Languages Using The Class Abstraction Jean-Pierre BRIOT Pierre COINTE LITP, University Paris-6 Rank Xerox France 4 Place Jussieu 12 Place de l'IRIS Paris, 75005 La Defense, 92071 mcvax!inria!litp!jpb mcvax!inria!litp!pc Abstract Object-oriented programming is built from the class model, introduced in the language Simula-67. In Simula, One of the main goals of object-oriented languages is to a class is a way to describe an abstract data structure. unify their universe: "every entity of the language is an ob• Active objects may be dynamically created from the class ject.* The class concept, however, usually does not follow description by instantiating the variables specified by the this wish: a class being not a real object, i.e., created from class. Such objects are called instances of the class. a class. The metaclass concept introduced in Smalltalk- B. Is a Class an Object? 80, attempts to give classes a first class citizenship but "With respect to Simula, Smalltalk abandons static scoping, to complicates the instantiation scheme without solving its gain flexibility in interactive use, and strong typing, allowing it fundamental limitations: the only partial specification of to implement system introspection and to introduce the notion of the class at the metaclass level, and the fixed number of metaclasses9 [4]. meta-levels. The object paradigm is set, and is now distinct from Some more recent approaches, as in Loops and then abstract data types systems. The Smalltalk language has CommonLoops, tend towards a better unification, but re• evolved from Smalltalk-72 [7] to Smalltalk-80 in order to veal the same limitations.
    [Show full text]