(OOP3) Classes, Methods & Objects
📔

(OOP3) Classes, Methods & Objects

 

Class Fundamentals

The data, or variables, defined within a class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class.

Declaring Objects

Box myBox = new Box(); // 'new' will dynamically allocate memory during runtime. // parentheses specify the constructor of the class (default).

Assigning Object Reference Variables

Box boxOne = new Box(); Box boxTwo = boxOne; // here, they both refer to the *same* object. no other memory allocation // or copy was made. any changes using boxTwo will affect boxOne.

Introducing Methods

class Box { // ... double volume() { return this.width * this.height * this.depth; } }

Returning Objects

class Box { // ... Box doubleDaBox() { Box boxCopy = new Box(this.width*2, this.height*2, this.depth*2); return boxCopy; } }

Static Methods & Variables

These are members that can be called without reference to any instances of the class (or objects). They can be accessed without any objects being created, and run as soon as their class is loaded. Static methods work on three conditions:
  1. They can only directly call other static methods of their class.
  1. They can only directly access static variables of their class.
  1. They cannot refer to this or super in any way.
(Only called by ClassName.method(), not classInstance.method().)
class UseStatic { static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[]) { meth(42); } }

Recursion

It is the process of defining something in terms of itself (like a method that calls itself).
class Factorial { int fact(int n) { int result; if (n == 1) return 1; result = fact(n-1) * n; return result; } } class Recursion { public static void main(String args[]) { Factorial factorial = new Factorial(); System.out.println("Factorial of 5 is " + factorial.fact(5)); } }

Constructors

DefaultConstructor.java
class Box { // ... (no-arg) Box() { System.out.println("Box class initialized."); } }
 
ParameterizedConstructor.java
class Box { // ... ('this' resolved namespace collisions.) Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; } }

Overloading Methods/Constructors

In Java, it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. This is known as method overloading, and showcases compile-time polymorphism.

Arguments & Parameters

Command-Line Arguments

class CommandLine { public static void main(String args[]) { for (int i = 0; i < args.length; i++) { System.out.println("args[" + i + "]: " + args[i]); } } }
PS F:\oopsies> java CommandLine this is a test 100 -1 args[0]: this args[1]: is args[2]: a args[3]: test args[4]: 100 args[5]: -1

Variable-Length Arguments (Varargs)

class VarArgs { static void vaTest(int ... v) { System.out.print("Number of args (int ...): " + v.length + " Contents: "); for (int x : v) // lay out the elements from "array". System.out.print(x + " "); System.out.println(); } static void vaTest(boolean ... v) { // overloading varargs. System.out.print("Number of args (boolean ...): " + v.length + " Contents: "); for (boolean x : v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { vaTest(10); vaTest(1, 2, 3); vaTest(true, false, false); // all parameters entered here will turn into an array. vaTest(); // Error: Ambiguous! } }

Access Control

An important attribute of encapsulation is access control. This makes sure that data can only be accessed through a few well-defined methods. Java’s access modifiers are public, private, and protected.
notion image
class Test { int a; public int b; private int c; void setC(int i) { c = i; } } class AccessTest { Test object = new Test(); // OK. object.a = 10; object.b = 20; // NOT OK. object.c = 100; object.setC(100); // OK. }

The Stack Class

class Stack { int stack[] = new int[10]; int top; Stack() { top = -1; } void push(int item) { if (top == 9) System.out.println("Stack overflow."); else stack[++top] = item; } int pop() { if (top < 0) { System.out.println("Stack underflow."); return 0; } else { return stack[top--]; } } }

The String Class

Every string created in Java is essentially an object of type String. Even String constants are actually String objects. These objects are immutable, BUT:
  • If you need to change a string, you can always create a copy with the required modifications.
  • Java defines peer classes of String, called StringBuffer and StringBuilder which allow strings to be altered.
Some of the common methods used on them are equals(), length() and charAt().