📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • Static Variables
  • Common use cases
  • Static Methods
  • Access in static methods
  • Common uses cases
  • Polymorphism and Overloading
  • Method signatures
  • Overloading
  • Why overload a method
  • Constructor overloading
  1. Java
  2. Intro To Java

Static Variables Methods And Polymorphism Using Overloading

Static Variables

Recall that instance variables are defined for each instance of a class. This has two effects:

  • Any instance can have unique variable values

  • An instance must be created in order to make use of instance variables

In contrast, static variables are the same for every instance of a class. You don't even need to instantiate a class to use them.

public class Employee {
  // static variable
  // NOTE: by convention, they're written in the form "STATIC_VARIABLE"
  static String COMPANY = "Acme Inc.";
  
  // instance variable 
  String name;
  public Employee(String name) {
    this.name = name;
  }
}

// Referencing static variable is done with the class itself
System.out.println(Employee.COMPANY); // prints "Acme Inc."

Pro tip: Static variables are most useful for hard-coded values that you are confident will not change.

Pro pro tip: If you are extremely confident that a static variable will never change, you can use the static final keyword instead.

Common use cases

One interesting use case is to store every instance created from a class in a static variable:

public class Employee {
  static ArrayList<Employee> EMPLOYEE_LIST = new ArrayList<Employee>();
  
  public Employee() {
    Employee.EMPLOYEE_LIST.add(this);
  }
}

This allows you to share data across every instance of a class.

Static Methods

Static methods are essentially the same thing as static variables but applied to methods instead.

Note: The public static void main method, the entry point for your entire application, is actually a static method! The runtime knows to run this static method to begin your application.

Access in static methods

Static methods:

  • Can only access static variables, not instance variables

  • Can call other static methods

  • Have no access to this

In contrast, instance methods:

  • Can access static variables

  • Can call static methods

Common uses cases

  • Helper methods

    • Example: Math.sqrt

  • Methods that don't require access to an instance and its variables to compute data

Polymorphism and Overloading

Method signatures

In Java, you can make multiple methods with the same name as long as they have either different types or sequences for their parameters:

public class Customer {
  // These are 2 different methods!
  void buy(String item) {}
  void buy(int itemCode) {}
}

These are known as the signature of a method.

Overloading

Polymorphism means "many shapes".

This breaks up into 2 distinct forms of polymorphism:

  • Overloading

    • Creating multiple methods with the same name but different signatures

  • Overriding

    • Overriding a class's inherited methods with another method with the same signature

Why overload a method

Overloading allows you to accommodate multiple data types. For example, System.out.println supports Strings, ints, doubles, etc. because it's been overloaded.

Also, overloading allows you to create a default case:

public class Counter {
  int count = 0;
  
  public void increment(int amount) {
    this..count += amount;
  }
  
  // What happens if you don't provide any argument
  public void increment() {
    this.increment(1);
  }
}

Finally, overloading allows you to stack possible outcomes for your methods:

public class Printer {
  public void print() {
    System.out.println("Hello");
  }
  
  // This version of `print` does the same thing as the original
  // but also prints a message you provide it!
  public void print(String message) {
    System.out.println(message);
    this.print();
  }
}

Constructor overloading

Constructor overloading is method overloading but with 2 extra rules:

  • Use the this keyword to call a constructor inside another constructor

  • The use of this to call a constructor must be the first thing the new constructor does

Best practice: Use constructor overloading when you want to do essentially the same thing but with different parameters. For example:

public class Point {
  int x;
  int y;
  
  // Shared behaviour for constructor!
  public Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
  // A default case when no arguments are provided!
  // (Using shared behaviour)
  public Point() {
    this(0, 0);
  }
}
PreviousUnit Testing Arrays And Array ListsNextJavascript

Last updated 2 years ago