Docsity

Lecture 18: Objects and Memory Management in CS031 - Prof. Pascal Hentenryck, Study notes of Computer Science

Partial preview of the text

Download Lecture 18: Objects and Memory Management in CS031 - Prof. Pascal Hentenryck and more Study notes Computer Science in PDF only on Docsity!

CS031 Lecture 18 (^) Page 1

CS

Pascal Van Hentenryck Objects

Overview

More data structures

  • Object without methods
  • methods
  • references

Allocating Objects

public class person { public char name[11]; public int age; public boolean employed; public int net_worth; }

  • arrange memory to be sure integers and floats are word-aligned
  • to pack or not to pack? (or, time vs space)

Data Declarations

.data name = 0 age = 12 empl = 16 # take a word worth = 20 psize = 24 pnum = 10 people: .word 240

Array of Objects

.data psize = 24 n = 10 people: .byte 240 .text #initialize all of the records la $s0,people li $s1,n loop: jal init_person add $s0,$s0,psize sub $s1,$s1, bnez $s1,loop

Methods in Objects

Methods are just procedures

  • the receiver is simply the first argument
  • the rest is just handled at compile-time

What is the compiler doing?

  • checking if the method can be applied
  • type checking
  • replacing this by the first argument
  • ...

What your JAVA Teachers Didn’t Tell You

and were right not to tell you

  • Objects are… MEMORY ADDRESSES! (no. really.)
  • Think of them as synonyms

Compiling Inheritance

class Animal { void eat(); void sleep(); } class Dog extends Animal { void eat(); void bark(); } class Cat extends Animal { void sleep(); void meow(); } How to compile a method typicalDay(Animal l) { l.eat(); l.sleep(); l.eat(); l.sleep(); … }

Compiling Inheritance

(dog) (ani) (cat) (ani)

Compiling Interfaces

class Animal { void eat(); } interface Mammal { void sleep(); void eat(); } class Dog extends Animal implements Mammal { void eat(); void sleep(); void bark(); }

Interfaces

bark.co

Linked Lists in Assembly

Conventions

  • Probably not what you learned in 15
  • More like car/cdr in Lisp class List { private int _key; private List _next; int getKey() { return _key; } List getNext() { return _next; } … }

Conventions

  • an empty list is represented by Null
  • the last element of the list has a Null _next field

Operations on Lists

  • Insert after X
  • Delete after X

Search For X

// _head is the head of the list; List search(int x) { List t0 = _head; while (t0 != null) { if (t0.getKey() == x) return t0; else t0 = t0.getNext(); } return null; }