Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Java and OO Terminology

This file contains terminology specific to Java and most other OO-based languages. While anyone is more than welcomed to use this, I created it primarily for my own benefit. Unfortunately, not many sources provide an easy-to-understand explanation, and if they do, the information is often scattered throughout several different site. To make it easier, I decided to take some Java and OO-based terminology that I myself have had trouble understanding and created this file containing that information.


Table of Contents
Table of Content

Static [1]

  • Fields (class variables)

    • Can only be declared at the class level.
    • Can be accessed without creating an object of the class in which they reside (object initialization).
    public class Car {
        // Declaring static variable.
        public static int numberOfDoors;
        // Declaring non-static variable.
        public int numberOfWheels;
        
        public static void main(String[] args) {
            /* When initializing a static class variable. */
            numberOfDoors = 4;
            
            /* When initializing a NON-static class variable. */
            Car newCar = new Car();
            newCar.numberOfWheels = 4;
        }
    }
  • Methods (class methods)

    • Can be called without creating an object of the class in which they reside (object initialization).
    • Can't be overridden.
    • Can't use this or super keywords.
    • ---------------------------------------------------------------
    • Abstract methods can't be static.
    • Instance methods can directly access both instance methods and instance variables.
    • Instance methods can also access static variables and static methods directly.
    • Static methods can access all static variables and other static methods.
    • Static methods can't access instance variables and instance methods directly; they need some object reference to do so.
    public class Car {
        // Used by static method.
        public static int numberOfCars;
        // Used by NON-static method.
        public static int numberOfCars2;
    
        /** Static method. */
        public static void setNumberOfCars(int numberOfCars) {
            numberOfCars = numberOfCars;
        }
        
        /** NON-static method */
        public void setNumberOfCars2(int numberOfCars2) {
            numberOfCars2 = numberOfCars2;
        }
    
        public static void main(String[] args) {
            /* When initializing a method WITH static */
            setNumberOfCars(10);
    
            /* When initializing a method WITHOUT static */
            Car newCar = new Car();
            newCar.setNumberOfCars2(5);
        }
    }
  • Class

    • Static nested classes do not have access to any instance members of the enclosing outer class; it can only access them through an object's reference.
    • Static nested classes can access all static members of the enclosing class, including private ones.
    • Java programming specification doesn't allow us to declare the top-level class as static; only classes within the classes (nested classes) can be made as static.
    public class Singleton  {    
        private Singleton() { }
        
        private static class SingletonHolder {    
            public static final Singleton instance = new Singleton();
        }    
    
        public static Singleton getInstance() {    
            return SingletonHolder.instance;    
        }    
    }

Access Modifiers [2]

Access Modifier Class Package Subclass (same pkg) Subclass (diff pkg) World
public + + + + +
protected + + + + -
no modifier (default) + + + - -
private + - - - -
  • + : Accessible
  • - : Not accessible

Is-A vs. Has-A [3]

Is-A:

  • Is-A relationship depends on inheritance.
  • Ensures code reusability.
  • Unidirectional
    • Example: A dog is an animal, but not every animal is a dog.
  • Is-A relationships utilize the extends and implements[1!] keywords.

Has-A:

  • Has-A relationship is also known as composition.
  • Ensures code reusability.
  • Unlike for an Is-A relationship, there are no keywords that implement a Has-A relationship.
  • The Has-A relationship simply means that an instance of one class has a reference to an instance of another class or another instance of the same class.

Has-A vs Is-A

Inheritance [4] [5]

  • Implements the Is-A relationship; parent-child relationship.
  • The ability of a subclass to acquire all the properties and behaviors of a superclass.
  • Utilizes the extends and implements[1!] keywords.
  • Two kinds of inheritance
    • Class inheritance
    • Interface inheritance
class Vehicle {
    protected String brand = "Ford";        // Vehicle attribute
    public void honk() {                    // Vehicle method
        System.out.println("Tuut, tuut!");
    }
}

class Car extends Vehicle {
    private String modelName = "Mustang";    // Car attribute
    public static void main(String[] args) {
        // Create a myCar object
        Car myCar = new Car();

        // Call the honk() method (from the Vehicle class) on the myCar object
        myCar.honk();

        // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
        System.out.println(myCar.brand + " " + myCar.modelName);
    }
}

Composition

  • Implements the Has-A relationship.
  • More information on composition can be found here

Association [6] [7] [8] [9]

Association refers to the relationship between multiple objects. It relates to how objects are related to each other and how they are using each other's functionality. Composition and aggregation are two types of association.

Aggregation [10]

  • Is a weak type of association.
  • An association between two objects that describes the Has-A relationship.
  • An association is said to be aggregation if both Objects can exist independently.
    • For example, a Team object and a Player object. The team contains multiple players, but a player can exist without a team.
  • Allows only one-to-one relationships.
// Team
public class Team {      
   // players can be 0 or more
   private List players;

   public Team () {
      players = new ArrayList();
   }
}
// Player Object
class Player {}

Composition [11]

  • Is a strong type of association.
  • Is a more specific type of aggregation that implies ownership. It describes a Belong-To/Has-A relationship.
  • An association is said to composition if an Object owns another object and another object cannot exist without the owner object.
    • Consider the case of a Human having a heart. Here Human object contains the heart, and the heart cannot exist without the Human.
  • Allows for one-to-many relationships between objects.
  • Allows us to dynamically change our program's behavior by changing the member objects at run time.
// Car must have Engine
public class Car {
   // engine is a mandatory part of the car
   private final Engine engine;

   public Car () {
      engine = new Engine();
   }
}

// Engine Object
class Engine { }

UML Notations

UML Representation

Abstract class and method [12] [13]

The abstract keyword is a non-access modifier used for classes and methods.

  • Class
    • Can have both abstract and regular methods.
    • Can have constructors and static methods.
  • Method
    • Can only be used in an abstract class.
    • Does not have a body; the body is provided by the inherit class.
    • Cannot be instantiated (used to create objects). To access it, it must be inherited from another class.
// Abstract class
abstract class Animal {
    // Abstract method (does not have a body)
    public abstract void animalSound();
    // Regular method
    public void sleep() {
        System.out.println("Zzz");
    }
}
    
// Subclass (inherit from Animal)
class Pig extends Animal {
    public void animalSound() {
        // The body of animalSound() is provided here
        System.out.println("The pig says: wee wee");
    }
}
    
class Main {
    public static void main(String[] args) {
        Pig myPig = new Pig(); // Create a Pig object
        myPig.animalSound();
        myPig.sleep();
    }
}

Interface [14]

  • Consists of only abstract methods.
  • On implementation of an interface, you must override all of its methods.
  • All attributes are by default public, static, and final.
  • Cannot be instantiated (used to create objects). To access it, it must be implemented by a different class. The interface can then be accessed via that class.
  • Does not have a body; the body is provided by the implement class.
  • Cannot contain instance variables, but can contain public static final variables (i.e., constant class variables).
  • Cannot contain a constructor (as it cannot be used to create objects).
// Interface
interface Animal {
    public void animalSound();  // Interface method (does not have a body)
    public void sleep();        // Interface method (does not have a body)
}

// Pig "implements" the Animal interface
class Pig implements Animal {
    public void animalSound() {
        // The body of animalSound() is provided here
        System.out.println("The pig says: wee wee");
    }
    public void sleep() {
        // The body of sleep() is provided here
        System.out.println("Zzz");
    }
}

class Main {
    public static void main(String[] args) {
        Pig myPig = new Pig();  // Create a Pig object
        myPig.animalSound();
        myPig.sleep();
    }
}

Abstract Class vs Interface

Differences [15]

Abstract Class Interface
Can have abstract and non-abstract methods. Can have only abstract methods. Since Java 8, it can have default and static methods also.
Doesn't support multiple inheritance. Supports multiple inheritance.
Can have final, non-final, static and non-static variables. Has only static and final variables.
Can provide the implementation of interface. Can't provide the implementation of abstract class.
The abstract keyword is used to declare an abstract class. The interface keyword is used to declare an interface.
Can extend another Java class and implement multiple Java interfaces. Can only extend another Java interface.
Can be extended using the keyword "extends". Can be implemented using keyword "implements".
A Java abstract class can have class members like private, protected, etc. Members of a Java interface are public by default.

Which should you use, abstract classes or interfaces? [16]

Based on the statements that apply to your situation, consider using one or the other:

Abstract Class Interface
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private) You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Clone-able are implemented by many unrelated classes.
You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong. You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
You want to share code among several closely related classes. You want to take advantage of multiple inheritance of type.

LinkedList vs ArrayList [17]

ArrayList LinkedList
This class uses a dynamic array to store the elements in it. With the introduction of generics, this class supports the storage of all types of objects. This class uses a doubly linked list to store the elements in it. Similar to the ArrayList, this class also supports the storage of all types of objects.
Manipulating ArrayList takes more time due to the internal implementation. Whenever we remove an element, internally, the array is traversed and the memory bits are shifted. Manipulating LinkedList takes less time compared to ArrayList because, in a doubly-linked list, there is no concept of shifting the memory bits. The list is traversed and the reference link is changed.
This class implements a List interface. Therefore, this acts as a list. This class implements both the List interface and the Deque interface. Therefore, it can act as a list and a deque.
This class works better when the application demands storing the data and accessing it. This class works better when the application demands manipulation of the stored data.

valueOf vs parseInt [18]

Integer.parseInt() Integer.valueOf()
It can only take a String as a parameter. It can take a String as well as an integer as parameter.
It returns a primitive int value. It returns an Integer object.
When an integer is passed as a parameter, it produces an error due to incompatible types. When an integer is passed as a parameter, it returns an Integer object corresponding to the given parameter.
This method produces an error(incompatible types) when a character is passed as parameter. This method can take a character as a parameter and will return the corresponding Unicode.
This lags behind in terms of performance since parsing a string takes a lot of time when compared to generating one. This method is likely to yield significantly better space and time performance by caching frequently requested values.
If we need the primitive int datatype then Integer.parseInt() method is to be used. If Wrapper Integer object is needed then valueOf() method is to be used.

Comparable vs Comparator [?]

NEEDS WORK/MORE CONTENT ADDED

Comparable:

  • Defines one methods
    • compareTo()
      • compares itself to o1

Comparator:

  • Defines two methods
    • compare(Object o1, Object o2)
      • compares o1 and o2
    • equals(Object o1)
      • Tests the equality of the invoking object (the object 'test' in 'test.equals(Object o1)') and o1

Terms that mean the same thing

Term Synonym 1 Synonym 2 Synonym 3 Synonym 4 Synonym 5
Variable Member Data fields
Superclass Parent class Base class
Subclass Child class Extended class Derived class

Sources

Notes

  • 1! I need to possibly do a bit more research to confirm this. While it makes sense, it's not something explicitly mentioned by many resources. As of now, only one source ([3]) that I use menthions that the implements keyword can represent a Is-A relationship.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment