Docsity

Classes, Inheritance, and Immutability in Java, Cheat Sheet of Computer science

Toggle sidebar
bg1
CSC245B Lab 2 – Prelab reading
Dr. Rasha Alkhansa
Spring 2024
Section 1 – Classes and Inheritance
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.
java.lang.Object )لكلا يب(
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:
• toString(): returns a String representation of the object (called implicitly whenever you print an
object or concatenate it with a String)
• clone(): returns a copy of the object
• equals(Object other): returns whether the self-object (this) is equal to the object passed as
argument (other).
When we created the Book class, it automatically inherited all the methods above. To verify that our
Book class inherits the methods in Object, create two Book objects, book1 and book2, then try the
following codes:
System.out.println(book1.toString()); //equivalent to System.out.print(book1)
System.out.println(book1.equals(book2));
(The clone() method cannot be used directly because it is not public.)
Note (common misconception): when we say that System.out.println(book1.toString()); is
equivalent to System.out.println(book1); it does not mean that book1 is equivalent to
book1.toString()! We are simply saying that the print method will call toString on our behalf.
pf3
pf4
pf5

Partial preview of the text

Download Classes, Inheritance, and Immutability in Java and more Cheat Sheet Computer science in PDF only on Docsity!

CSC245B Lab 2 – Prelab reading

Dr. Rasha Alkhansa

Spring 2024

Section 1 – Classes and Inheritance

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.

java.lang.Object (بي الكل)

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:

  • toString(): returns a String representation of the object (called implicitly whenever you print an object or concatenate it with a String)
  • clone(): returns a copy of the object
  • equals(Object other): returns whether the self-object ( this ) is equal to the object passed as argument ( other ). When we created the Book class, it automatically inherited all the methods above. To verify that our Book class inherits the methods in Object, create two Book objects, book1 and book2, then try the following codes: System. out .println(book1.toString()); //equivalent to System.out.print(book1) System. out .println(book1.equals(book2)); (The clone() method cannot be used directly because it is not public.) Note (common misconception): when we say that System. out .println(book1.toString()); is equivalent to System. out .println(book1); it does not mean that book1 is equivalent to book1.toString()! We are simply saying that the print method will call toString on our behalf.

Overriding inherited methods

It is common to override the default implementations of the inherited methods. Examples:

  • toSting() returns a String that is a function of the memory location of the object (you will see that if you try the codes above). Typically, we would want a different String representation, for example, we might want the book to be represented by its title and author , rather than by its memory location.
  • equals() by default is equivalent to ==, that is, it returns if the two references are aliases (i.e., if they are pointing to the same memory location.. more explanation on this in the next section). So even if book1 and book2 have the same title, author, and publication year, comparing them with equals will return false by default unless if they are aliases. We might want to change (override) this default behavior, and this is what you will do in lab 2.
  • clone() has a default implementation that is good enough, but the method is not public, so we need to override its visibility to public. In lab1, you will override the visibility of the clone method, and you will also give your own implementation for it (although we can reuse the inherited implementation, but this would require some extra coding related to exception handling which we will not deal with in this lab).

== vs. equals

  • For primitive types (int, double, boolean, etc.), the equality check == checks if the values are equal
  • For reference types (e.g., String or Book), == checks if the objects are aliases (see more explanation in the next section)
  • The equals method can only be used with reference types, and as mentioned above, it is equivalent by default to ==: for example, book1.equals(book2) is equivalent to book1==book assuming that the default behavior of equals is not overridden. However, typically, equals is overridden to compare contents and attributes (not memory locations).

Conclusions:

  • All classes in Java inherit directly or indirectly from the Object class which

provides some useful methods like toString, clone, and equals. We can

directly use these methods with their default implementations, or we can

override their behavior for our newly created types.

  • The proper way of comparison for primitive types (e.g., int, double) is using

==, whereas the proper way of comparison for reference types (e.g., String,

Book) is using the equals method which is inherited from Object.

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.

So, which is better?

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:

  • It is safe: immutability allows for avoiding unintended mutations and thus avoiding potential logical/runtime errors.
  • Because it is safe, we can make many aliases pointing to the same memory location, thus saving memory space: this is actually used for the String type, where Java keeps a pool of the commonly used String literals to be re-used: when a String object is created using this syntax: String s = “hello” , if an object “hello” already exists in memory, then s will be safely made an alias to it (no new object created unnecessarily). On the other hand, if the String object is created using the new keyword (not recommended): String s = new String(“hello”) , then the creation of a new String object is forced. Disadvantage of immutability:
  • Generally poorer performance (slower running time) when mutations occur. As shown in the examples above, appending just one character to a String requires copying all the old characters (could be many!) into a new memory location before appending the new character. This is not needed for StringBuilder where the mutation happens quickly in-place.

Conclusion : immutability is one way to avoid the risks of shallow copying. For

example, you can always copy String objects using the assignment operator

without worrying about the risks of shallow copying, because String is immutable

and any changes to one String reference will not really change its content but

rather create a new String and make it point to it without affecting the old String

or any aliases pointing to it.