



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




In lab 1, you saw an example of a class definition, where a new reference type Book was created. You have also seen example usage of the Book type and how objects of type Book can be created using the new keyword. Another object-oriented functionality in Java is inheritance. In Java, a class can inherit another class. For example, we can create a Person class which represents person objects and includes attributes of a person (e.g., name, age), and we can also create subclasses of Person (classes that inherit the attributes and methods of Person). For example, Student , Teacher , and Musician can be defined as classes that inherit from the class Person because students, teachers, and musicians are people, and therefore, they inherit all the attributes of a Person.This is very brief idea about what inheritance is; you will learn about it in detail in later lectures and labs.
For the sake of this week’s lab, you are only required to know that all classes in Java inherit (directly or indirectly) from the class Object (java.lang.Object), which means that they inherit all the methods defined in this class. Only the class Object itself does not have a parent class (it is on the top of the inheritance hierarchy). Examples of methods inherited from java.lang.Object:
It is common to override the default implementations of the inherited methods. Examples:
Section 3 – Immutability The String type in Java is immutable. This means that a String object at a given memory location cannot be mutated, and even if you attempt to mutate (by concatenating additional characters for example), the contents of the existing memory location do not change; instead, a new String object (in a new memory location) is created to hold the modified value, leaving the old location unchanged, as demonstrated in the example below. On the other hand, StringBuilder is another type in Java which is similar to String, but it is mutable; that is, StringBuilder has methods that mutate the object (at the same memory location), as shown in the example below. In both of the examples above, the outcome is “ab”, so what is the difference? Mutability impacts are mainly seen when multiple references point to the same object in memory. If a mutable object is modified, all aliases are affected, whereas if it is immutable, then the aliases are not affected, as illustrated in the example below.
Is it better to use the immutable String or the mutable StringBuilder? Answer: it depends. See the pros and cons on the next page.
Advantages of immutability: