A Runtime Assertion Checker for the Java Modeling Language Yoonsik Cheon Iowa State University

Total Page:16

File Type:pdf, Size:1020Kb

A Runtime Assertion Checker for the Java Modeling Language Yoonsik Cheon Iowa State University Iowa State University Capstones, Theses and Retrospective Theses and Dissertations Dissertations 2003 A runtime assertion checker for the Java Modeling Language Yoonsik Cheon Iowa State University Follow this and additional works at: https://lib.dr.iastate.edu/rtd Part of the Computer Sciences Commons Recommended Citation Cheon, Yoonsik, "A runtime assertion checker for the Java Modeling Language " (2003). Retrospective Theses and Dissertations. 570. https://lib.dr.iastate.edu/rtd/570 This Dissertation is brought to you for free and open access by the Iowa State University Capstones, Theses and Dissertations at Iowa State University Digital Repository. It has been accepted for inclusion in Retrospective Theses and Dissertations by an authorized administrator of Iowa State University Digital Repository. For more information, please contact [email protected]. A runtime assertion checker for the Java Modeling Language by Yoonsik Cheon A dissertation submitted to the graduate faculty in partial fulfillment of the requirements for the degree of DOCTOR OF PHILOSOPHY Major: Computer Science Program of Study Committee: Gary T. Leavens, Major Professor Les Miller Robyn R. Lutz Don L. Pigozzi Clifford Bergman Iowa State University Ames, Iowa 2003 Copyright © Yoonsik Cheon, 2003. All rights reserved. UMI Number: 3085895 Copyright 2003 by Cheon, Yoonsik All rights reserved. UMI UMI Microform 3085895 Copyright 2003 by ProQuest Information and Learning Company. All rights reserved. This microform edition is protected against unauthorized copying under Title 17, United States Code. ProQuest Information and Learning Company 300 North Zeeb Road P.O. Box 1346 Ann Arbor, Ml 48106-1346 ii Graduate College Iowa State University This is to certify that the doctoral dissertation of Yoonsik Cheon has met the dissertation requirements of Iowa State University Signature was redacted for privacy. Majot rrofessor Signature was redacted for privacy. For the Major Program iii TABLE OF CONTENTS LIST OF TABLES ix LIST OF FIGURES x ACKNOWLEDGEMENTS xiv ABSTRACT xv 1 INTRODUCTION 1 1.1 Background 1 1.1.1 Runtime Assertion Checking 3 1.1.2 The Java Modeling Language 5 1.2 Objectives 7 1.3 The Problem 9 1.3.1 Semantic Discrepancies between JML and Java 9 1.3.2 Advanced Features of JML 10 1.3.3 Research Scope 12 1.4 Approach 12 1.4.1 What, Where, and When to Check? 12 1.4.2 Assertion Blocks, Methods, and Classes 14 1.4.3 Local, Contextual Interpretation 16 1.4.4 Dynamic Delegation 16 1.4.5 Access Methods 17 1.5 Implementation 18 1.5.1 The JML Compiler 19 iv 1.5.2 Reporting Assertion Violations 21 1.6 Application — Specifications as Test Oracles 22 1.7 Contributions 24 1.8 Outline 25 2 AN OVERVIEW OF JML 27 2.1 Introduction 27 2.2 Assertions and Expressions 29 2.3 Method Specifications 31 2.3.1 Specification Clauses 31 2.3.2 Heavyweight versus Lightweight 32 2.3.3 Syntactic Sugars 33 2.3.4 Privacy of Specifications 34 2.3.5 Semantics 34 2.4 Type Specifications 35 2.4.1 Invariants 35 2.4.2 Constraints 36 2.4.3 Abstract Specifications 37 2.5 Inheritance of Specifications 38 2.6 An Example 39 2.7 Discussion 42 3 EXPRESSIONS AND ASSERTIONS 44 3.1 Introduction 44 3.1.1 Notations 46 3.2 The Undefinedness Problem 48 3.2.1 An Example 49 3.2.2 Demonic versus Angelic 50 3.2.3 Contextual Interpretation 50 3.2.4 Translation Rules 52 V 3.2.5 Non-executable Constructs 57 3.3 Quantified Expressions 59 3.3.1 Abstract Syntax Extended 59 3.3.2 Semantic Clarification 59 3.3.3 Pattern-based Static Analysis 61 3.4 Related Work 64 3.4.1 Undefinedness 64 3.4.2 Quantified Expressions 66 3.5 Discussion 69 3.5.1 Anomaly of Contextual Interpretation 69 3.5.2 Referring to Pre-state Expressions 70 3.5.3 Other Approaches to Quantifiers 71 3.6 Summary 72 4 METHOD SPECIFICATIONS 73 4.1 Introduction 73 4.1.1 Reporting Assertion Violations 75 4.1.2 Translation Scheme 76 4.1.3 Wrapper Approach 78 4.1.4 Outline 79 4.2 Desugaring Specifications 80 4.2.1 Eliminating Old Variables 83 4.2.2 Eliminating Old Expressions 84 4.3 Wrapper Methods 84 4.4 Precondition Methods . 87 4.5 Postcondition Methods 89 4.5.1 Normal Postconditions 89 4.5.2 Exceptional Postconditions 90 4.6 Pre-state Expressions 94 vi 4.7 In-line Assertions 96 4.7.1 Assertions, Assumptions, and Reasons 96 4.7.2 Unreachable Statements 98 4.7.3 Set Statements 98 4.7.4 Loop Invariants and Variants 99 4.8 Discussion 104 4.8.1 Privacy of Method Specifications 104 4.8.2 Constructors and Finalizers 105 4.8.3 Initializers 106 5 TYPE SPECIFICATIONS 107 5.1 Introduction 107 5.2 Invariants Ill 5.3 Constraints 112 5.3.1 Old Expressions 112 5.3.2 Nested Method Calls 115 5.3.3 Method-specific Constraints 117 5.4 Wrapper Methods Revisited 119 5.5 Specifications for Interfaces 119 5.6 Discussion 122 5.6.1 Limitations 122 5.6.2 Establishing Static Invariants 123 5.6.3 Privacy of Specifications 124 6 INHERITANCE OF SPECIFICATIONS 126 6.1 Introduction 126 6.1.1 Challenges 127 6.1.2 Approach 128 6.1.3 Delegation Approach 128 6.2 Method Specifications 130 vii 6.2.1 Immediate Supertypes for Specification Inheritance 131 6.2.2 Preconditions 132 6.2.3 Normal Postconditions 135 6.2.4 Exceptional Postconditions 135 6.3 Invariants 137 6.4 Constraints 139 6.4.1 Weak Behavioral Subtyping 141 6.5 Specifications for Interfaces 143 6.5.1 Propagating Assertion Calls to Superinterfaces 148 6.5.2 Lazy Initialization of Surrogate Maps 150 6.6 An Example 150 6.7 Discussion 151 6.7.1 Anomaly of Specification Inheritance 152 6.7.2 Checking Behavioral Subtyping 155 6.7.3 Refinement 155 7 ABSTRACT SPECIFICATIONS 158 7.1 Introduction 159 7.1.1 Abstraction in JML 159 7.1.2 General Approach 159 7.2 Model Fields 161 7.2.1 Model Field Access Methods 161 7.2.2 Assertions with Model Fields 162 7.2.3 Inheritance 164 7.3 Interface Model Fields 166 7.3.1 Inheritance 167 7.3.2 Details of the Approach 171 7.3.3 An Example 174 7.4 Ghost Fields 177 viii 7.5 Model Methods 179 7.6 Discussion 183 8 APPLICATION — UNIT TESTING WITH JML 185 8.1 Introduction 185 8.1.1 The Problem 186 8.1.2 Approach 187 8.1.3 Outline 188 8.2 Assumptions About the Specification Language 189 8.2.1 The Runtime Assertion Checker 190 8.3 Assumptions About the Testing Framework 191 8.4 Test Oracle Generation 193 8.4.1 Deciding Test Outcomes 193 8.4.2 Setting Up Test Cases 195 8.4.3 Test Methods 198 8.4.4 Test Classes 200 8.5 Test Execution 200 8.5.1 Supplying Test Cases 200 8.5.2 Running the Tests 201 8.6 Related Work 205 8.7 Summary 207 9 CONCLUSION 209 9.1 Future Work 209 9.2 Summary 211 ix LIST OF TABLES Table 2.1 JML's extension to Java's expressions 30 Table 2.2 Method specification clauses 31 Table 3.1 Translation contexts for expressions 52 X LIST OF FIGURES Figure 1.1 Compilation-based approach to runtime assertion checking 19 Figure 1.2 Architecture of the JML compiler 20 Figure 2.1 Example JML specification 28 Figure 2.2 Desugaring specification cases 33 Figure 2.3 Desugaring nested specifications 34 Figure 2.4 Specification of the class StackAsArray 40 Figure 3.1 Abstract syntax of JML expressions and sample translation rule. ... 47 Figure 3.2 JML specification with potential undefinedness 48 Figure 3.3 Translating field reference expressions 53 Figure 3.4 Translating method call expressions 55 Figure 3.5 Translating equivalence, implication, and negation expressions 56 Figure 3.6 Translating conditional expressions 57 Figure 3.7 Translating equality expressions 58 Figure 3.8 Extended abstract syntax of JML expressions 59 Figure 3.9 Translating the universal quantifier 63 Figure 4.1 Class hierarchy of assertion violation errors 77 Figure 4.2 Control flow of the wrapper approach 80 Figure 4.3 General structure of wrapper methods 86 Figure 4.4 General structure of precondition methods 88 Figure 4.5 General structure of normal postcondition methods 90 Figure 4.6 Method specifications with signals clauses 91 xi Figure 4.7 General structure of exceptional postcondition methods (part 1). 92 Figure 4.8 General structure of exceptional postcondition methods (part 2). 93 Figure 4.9 Evaluating old expressions 95 Figure 4.10 Example of old variables 95 Figure 4.11 Translating assert and assume statements 97 Figure 4.12 Ghost fields and set statements 99 Figure 4.13 Translating set statements 99 Figure 4.14 Translating loop invariants and variants for while statements 101 Figure 4.15 Translating loop invariants and variants for do statements 103 Figure 4.16 Translating loop invariants and variants for for statements 104 Figure 5.1 Control flow for checking type assertions 109 Figure 5.2 Instance and static invariant methods Ill Figure 5.3 Instance and static constraint methods 113 Figure 5.4 Evaluating old expressions appearing in constraints 114 Figure 5.5 Constraints and nested method calls 115 Figure 5.6 Referring to correct pre-state values in nested assertion checking. 116 Figure 5.7 Old value stacks generated by the JML compiler 116 Figure 5.8 Extended and new constraint methods for method-specific constraints.
Recommended publications
  • The Java Modeling Language
    The Java Modeling Language Software Fiável Mestrado em Engenharia Informática Mestrado em Informática Faculdade de Ciências da Universidade de Lisboa 2015/2016 Vasco T. Vasconcelos, Antónia Lopes Software Fiável The Java Modeling Language Contracts I The key ingredient of Design by contract, software design methodology promoted by Bertrand Meyer and the Eiffel programming language in 1986. I Inspired by assertions of Hoare logic, contracts place special obligations on both clients and suppliers of a procedure or method. I What does a method require from it’s caller? I What does the method ensure? Software Fiável The Java Modeling Language DBC DBC key idea is to associate a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. I Forces the programmer to write exactly what the method does and needs I No need to program defensively (defensive checks can be exensive and increases the complexity of the code of the method and worsen its maintainability) I Assigns blame: specifies who is to blame for not keeping the contract I Provides a standard way to document classes: client programmers are provided with a proper description of the interface properties of a class that is stripped of all implementation information but retains the essential usage information: the contract. Software Fiável The Java Modeling Language Language support for Contracts Language support for contracts exists in different forms: I Eiffel is an object-oriented language that includes contracts I JML adds contracts to the Java language. JML specifications are conventional Java boolean expressions, with a few extensions I Spec# adds contracts to C# I Code Contracts is an API (part of .NET) to author contracts In this course we focus on JML.
    [Show full text]
  • Génération Automatique De Tests Unitaires Avec Praspel, Un Langage De Spécification Pour PHP the Art of Contract-Based Testing in PHP with Praspel
    CORE Metadata, citation and similar papers at core.ac.uk Provided by HAL - Université de Franche-Comté G´en´erationautomatique de tests unitaires avec Praspel, un langage de sp´ecificationpour PHP Ivan Enderlin To cite this version: Ivan Enderlin. G´en´eration automatique de tests unitaires avec Praspel, un langage de sp´ecificationpour PHP. Informatique et langage [cs.CL]. Universit´ede Franche-Comt´e,2014. Fran¸cais. <NNT : 2014BESA2067>. <tel-01093355v2> HAL Id: tel-01093355 https://hal.inria.fr/tel-01093355v2 Submitted on 19 Oct 2016 HAL is a multi-disciplinary open access L'archive ouverte pluridisciplinaire HAL, est archive for the deposit and dissemination of sci- destin´eeau d´ep^otet `ala diffusion de documents entific research documents, whether they are pub- scientifiques de niveau recherche, publi´esou non, lished or not. The documents may come from ´emanant des ´etablissements d'enseignement et de teaching and research institutions in France or recherche fran¸caisou ´etrangers,des laboratoires abroad, or from public or private research centers. publics ou priv´es. Thèse de Doctorat école doctorale sciences pour l’ingénieur et microtechniques UNIVERSITÉ DE FRANCHE-COMTÉ No X X X THÈSE présentée par Ivan Enderlin pour obtenir le Grade de Docteur de l’Université de Franche-Comté K 8 k Génération automatique de tests unitaires avec Praspel, un langage de spécification pour PHP The Art of Contract-based Testing in PHP with Praspel Spécialité Informatique Instituts Femto-ST (département DISC) et INRIA (laboratoire LORIA) Soutenue publiquement
    [Show full text]
  • OOP with Java 16
    OOP with Java 16. Inheritance and Overriding Thomas Weise · 汤卫思 [email protected] · http://iao.hfuu.edu.cn Hefei University, South Campus 2 合肥学院 南艳湖校区/南2区 Faculty of Computer Science and Technology 计算机科学与技术系 Institute of Applied Optimization 应用优化研究所 230601 Shushan District, Hefei, Anhui, China 中国 安徽省 合肥市 蜀山区 230601 Econ. & Tech. Devel. Zone, Jinxiu Dadao 99 经济技术开发区 锦绣大道99号 Outline 1 Introduction 2 Extending Classes and Class Hierarchy 3 Multi-Level Inheritance 4 The Class Object 5 static vs. instance methods 6 Summary website OOPwithJava ThomasWeise 2/23 Introduction • So far, we have basically treated as objects as data structures and used methods to work on them OOPwithJava ThomasWeise 3/23 Introduction • So far, we have basically treated as objects as data structures and used methods to work on them • But Object-Oriented Programming is much more OOPwithJava ThomasWeise 3/23 Introduction • So far, we have basically treated as objects as data structures and used methods to work on them • But Object-Oriented Programming is much more • The true power of OOP arises from class inheritance and extension (often called specialization) OOPwithJava ThomasWeise 3/23 Extending Classes • A class Student can extend another class Person OOPwithJava ThomasWeise 4/23 Extending Classes • A class Student can extend another class Person • Student inherits all the fields and functionality of the original class Person OOPwithJava ThomasWeise 4/23 Extending Classes • A class Student can extend another class Person • Student inherits all the fields and functionality
    [Show full text]
  • Programming in JAVA Topic: • a Closer Look at Methods And
    B. Sc. (H) Computer Science Semester II BHCS03 – Programming in JAVA Topic: A Closer Look at Methods and Classes Inheritance Command Line Arguments The java command-line argument is an argument i.e. passed at the time of running the java program. The arguments passed from the console can be received in the java program and it can be used as an input. So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt. Simple example of command-line argument In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one argument from the command prompt. class CommandLineExample{ public static void main(String args[]){ System.out.println("Your first argument is: "+args[0]); } } compile by > javac CommandLineExample.java run by > java CommandLineExample sonoo Output: Your first argument is: sonoo Varargs: Variable length arguments A method with variable length arguments(Varargs) in Java can have zero or multiple arguments. Variable length arguments are most useful when the number of arguments to be passed to the method is not known beforehand. They also reduce the code as overloaded methods are not required. Example public class Demo { public static void Varargs(String... str) { System.out.println("\nNumber of arguments are: " + str.length); System.out.println("The argument values are: "); for (String s : str) System.out.println(s); } public static void main(String args[]) { Varargs("Apple", "Mango", "Pear"); Varargs(); Varargs("Magic"); } } Output Number of arguments are: 3 The argument values are: Apple Mango Pear Number of arguments are: 0 The argument values are: Number of arguments are: 1 The argument values are: Magic Overloading Varargs Methods Overloading allows different methods to have same name, but different signatures where signature can differ by number of input parameters or type of input parameters or both.
    [Show full text]
  • The Java Modeling Language
    The Java Modeling language JML Erik Poll Digital Security Radboud University Nijmegen JML • formal specification language for sequential Java by Gary Leavens et. al. – to specify behaviour of Java classes & interfaces – to record detailed design decisions by adding annotations to Java source code in Design-By- Contract style, using eg. pre/postconditions and invariants • Design goal: meant to be usable by any Java programmer Lots of info on http://www.jmlspecs.org Erik Poll, JML introduction - CHARTER meeting - 2 to make JML easy to use • JML annotations added as special Java comments, between /*@ .. @*/ or after //@ • JML specs can be in .java files, or in separate .jml files • Properties specified using Java syntax, extended with some operators \old( ), \result, \forall, \exists, ==> , .. and some keywords requires, ensures, invariant, .... Erik Poll, JML introduction - CHARTER meeting - 3 JML example public class ePurse{ private int balance; //@ invariant 0 <= balance && balance < 500; //@ requires amount >= 0; //@ ensures balance <= \old(balance); public debit(int amount) { if (amount > balance) { throw (new BankException("No way"));} balance = balance – amount; } Erik Poll, JML introduction - CHARTER meeting - 4 What can you do with this? • documentation/specification – record detailed design decisions & document assumptions (and hence obligations!) – precise, unambiguous documentation • parsed & type checked • use tools for – runtime assertion checking • eg when testing code – compile time (static) analyses • up to full formal program
    [Show full text]
  • Module 3 Inheritance in Java
    Module 3 Inheritance in Java Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also. Inheritance represents the IS-A relationship, also known as parent-child relationship. For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability. Syntax of Java Inheritance class Subclass-name extends Superclass-name { KTUNOTES.IN //methods and fields } The extends keyword indicates that you are making a new class that derives from an existing class. In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass. As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee. class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } Programmer salary is:40000.0 Bonus of programmer is:10000 In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability. Downloaded from Ktunotes.in Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel hierarchical.
    [Show full text]
  • You Say 'JML' ? Wikipedia (En)
    You say 'JML' ? Wikipedia (en) PDF generated using the open source mwlib toolkit. See http://code.pediapress.com/ for more information. PDF generated at: Mon, 06 Jan 2014 09:58:42 UTC Contents Articles Java Modeling Language 1 Design by contract 5 Formal methods 10 References Article Sources and Contributors 15 Image Sources, Licenses and Contributors 16 Article Licenses License 17 Java Modeling Language 1 Java Modeling Language The Java Modeling Language (JML) is a specification language for Java programs, using Hoare style pre- and postconditions and invariants, that follows the design by contract paradigm. Specifications are written as Java annotation comments to the source files, which hence can be compiled with any Java compiler. Various verification tools, such as a runtime assertion checker and the Extended Static Checker (ESC/Java) aid development. Overview JML is a behavioural interface specification language for Java modules. JML provides semantics to formally describe the behavior of a Java module, preventing ambiguity with regard to the module designers' intentions. JML inherits ideas from Eiffel, Larch and the Refinement Calculus, with the goal of providing rigorous formal semantics while still being accessible to any Java programmer. Various tools are available that make use of JML's behavioral specifications. Because specifications can be written as annotations in Java program files, or stored in separate specification files, Java modules with JML specifications can be compiled unchanged with any Java compiler. Syntax JML specifications are added to Java code in the form of annotations in comments. Java comments are interpreted as JML annotations when they begin with an @ sign.
    [Show full text]
  • Conformity Behavior of Dissimilar Methods for Object Oriented
    K. LOUZAOUUI Conformity behavior of dissimilar methods for object oriented constraint programming 212 Conformity Behavior of Dissimilar Methods for Object Oriented Constraint Programming Khadija Louzaoui Khalid Benlhachmi Department of Mathematics Department of Computer Sciences Faculty of Sciences, Ibn Tofail University Faculty of Sciences, Ibn Tofail University Kenitra, Morocco Kenitra, Morocco Abstract—This paper presents an approach for testing the number of test cases is infinite, therefore, testing is very conformity of overridden and overriding methods using expensive. So, how to select the most proper set of test cases? inheritance principle. The first objective of this work is the In practice, various techniques are used for that, some of them reduction of the test sequences by using only one generation of are based on the specification of the program under test using test data. The second result is the conformity testing of methods precondition, postcondition and invariant constraints. In this even if they are not similar: Our approach shows how the similarity partitioning can be used for testing not the similarity way the specifications by constraints in an object oriented behavior between methods but the conformity behavior of paradigm can be specified by formal languages as OCL [3] and subclasses for an object oriented model. JML [4], and are used for generating test data from formal specifications [5]. This software verification by constraints can In this work we use a mathematical modeling such as domain help for creating a mathematical modeling and building the partitioning and states graph for testing the conformity of parts of different classes of errors (equivalence partitioning).
    [Show full text]
  • JAVA - OVERRIDING Copyright © Tutorialspoint.Com
    JAVA - OVERRIDING http://www.tutorialspoint.com/java/java_overriding.htm Copyright © tutorialspoint.com In the previous chapter, we talked about super classes and sub classes. If a class inherits a method from its super class, then there is a chance to override the method provided that it is not marked final. The benefit of overriding is: ability to define a behavior that's specific to the subclass type which means a subclass can implement a parent class method based on its requirement. In object-oriented terms, overriding means to override the functionality of an existing method. Example: Let us look at an example. class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); } } public class TestDog{ public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class } } This would produce the following result: Animals can move Dogs can walk and run In the above example, you can see that the even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object. Therefore, in the above example, the program will compile properly since Animal class has the method move.
    [Show full text]
  • Method Overriding
    Method Overriding OOC 4th Sem, ‘B’ Div 2016-17 Prof. Mouna M. Naravani ➢ In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. ➢ When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. ➢ The version of the method defined by the superclass will be hidden. class A { class B extends A { int i, j; int k; A(int a, int b) { B(int a, int b, int c) { i = a; super(a, b); j = b; k = c; } } // display i and j // display k -- this overrides show() in A void show() { void show() { System.out.println("i and j: " + i + " " + j); System.out.println("k: " + k); } } } } class Override { Output: public static void main(String args[]) k : 3 { B subOb = new B(1, 2, 3); subOb.show(); // this calls show() in B } } ➢ When show( ) is invoked on an object of type B, the version of show( ) defined within B is used. ➢ That is, the version of show( ) inside B overrides the version declared in A. ➢ If you wish to access the superclass version of an overridden method, you can do so by using super. class B extends A { int k; B(int a, int b, int c) { super(a, b); Output: k = c; i and j : 1 2 } k : 3 void show() { super.show(); // this calls A's show() System.out.println("k: " + k); } } ➢ Method overriding occurs only when the names and the type signatures of the two methods are identical.
    [Show full text]
  • Introduction to JML the Java Modeling Language
    Goal: JML should be easy to use for any Java programmer. Outline of this tutorial First • introduction to JML Introduction to JML • overview of tool support for JML, esp. runtime assertion checking (using jmlrac) and extended static David Cok, Joe Kiniry, and Erik Poll checking ESC/Java2 Then Eastman Kodak Company, University College Dublin, • ESC/Java2: Use and Features and Radboud University Nijmegen • ESC/Java2: Warnings • Specification tips and pitfalls • Advanced JML: more tips and pitfalls interspersed with demos. David Cok, Joe Kiniry & Erik Poll - ESC/Java2 & JML Tutorial – p.1/30 David Cok, Joe Kiniry & Erik Poll - ESC/Java2 & JML Tutorial – p.2/30 JML by Gary Leavens et al. Formal specification language for Java • to specify behaviour of Java classes • to record design &implementation decisions The Java Modeling Language by adding assertions to Java source code, eg • preconditions JML • postconditions • invariants www.jmlspecs.org as in Eiffel (Design by Contract), but more expressive. David Cok, Joe Kiniry & Erik Poll - ESC/Java2 & JML Tutorial – p.3/30 David Cok, Joe Kiniry & Erik Poll - ESC/Java2 & JML Tutorial – p.4/30 JML by Gary Leavens et al. JML Formal specification language for Java To make JML easy to use: to specify behaviour of Java classes • • JML assertions are added as comments in .java file, • to record design &implementation decisions between /*@ . @*/, or after //@, by adding assertions to Java source code, eg • Properties are specified as Java boolean expressions, extended with a few operators (nold, nforall, nresult, • preconditions . ). • postconditions • using a few keywords (requires, ensures, • invariants signals, assignable, pure, invariant, non null, .
    [Show full text]
  • Unit 2 – Part 4. Polymorphism(OOP)
    Unit 2 – part 4. Polymorphism(OOP) BCIS 222. Object Oriented Programming Instructor: Dr. Carlo A. Mora LMS: http://l earn.nmsu.ed u OOP Principles y Piece of Cake!! A (Abstraction) E P (Encapsulation) (Polymorphism) I (Inheritance) protected Members y Intermediate level of protection between public and private y prottdtected members accessible to y superclass members y subclass members y Clbhlass members in the same namespace y Subclass access superclass member y Keyword base and a dot (.) y E.g. base.toString() y Method overloading vs. Method overriding y Overloading Having several methods with same name but different parameters y Overriding redefining a method in a subclass y How to access and overridden method? super keyword UiUsing protec tdted iitnstance variiblables y Advantages y subclasses can modify values directly y Slight increase in performance y Avoid set/get function call overhead y Disadvantages y No validityyg checking y subclass can assign illegal value y Implementation dependent y subcl ass method s more likliklely depend ent on superclass iilmplemen ta tion y superclass implementation changes may result in subclass modifications y Fragile (brittle) software Wrapping up the Case Study y What advantages do we have by having a class Hierarchy? y No need to declare common members in subclasses (e.g. name) y Simplified version of methods (e.g. toString) y Wha t is the purpose of y GetGraduationDate method? y Rethink the TestClass y What if I need to create an array to hold different types of students? Polymorphism y Dictionary
    [Show full text]