Vocab

Creating a Class

Classes can be created by using the keyword "class",followed by defining the class name starting with a single uppercase letter (known as CamelCase).

Format:

class ClassName {
    // code
}

Constructor

  • Special method used to initialize objects

  • Constructor does not return anything because it's not called directly by the code, it's called by the memory allocation and object initialization code in the runtime. Its return value (if it actually has one when compiled down to machine code) is opaque to the user - therefore, you can't specify it.

// Create a Main class
public class Main {
    int x;  // Create a class attribute
  
    // Create a class constructor for the Main class
    public Main() {
      x = 5;  // Set the initial value for the class attribute x
    }
  
    public static void main(String[] args) {
      Main myObj = new Main(); // Create an object of class Main (This will call the constructor)

      System.out.println(myObj.x); // Print the value of x
    }
  }
  
  Main.main(null);
  // Outputs 5
5

Accessor Methods

  • return the value of a private variable

  • gives other classes access to that value stored in that variable, without having direct access to the variable itself

  • Accessor methods take no parameters and have a return type that matches the type of the variable they are accessing.

Mutator Methods

  • reset the value of a private variable

  • gives other classes the ability to modify the value stored in that variable without having direct access to the variable itself

  • take one parameter whose type matches the type of the variable it is modifying

  • always have a return type of whatever data field is being retrieved

Static Variables

  • also called class variables, as they belong to the class and not a particular instance

public class Demo{
    public static void main(String args[]){
      Student s1 = new Student();
      s1.showData();
      Student s2 = new Student();
      s2.showData();
      //Student.b++;
      //s1.showData();
   }
 }
 
 class Student {
 int a; //initialized to zero
 static int b; //initialized to zero only when class is loaded not for each object created.
 
   Student(){
    //Constructor incrementing static variable b
    b++;
   }
 
    public void showData(){
       System.out.println("Value of a = "+a);
       System.out.println("Value of b = "+b);
    }
 //public static void increment(){
 //a++;
 //}
 
 }

 Demo.main(null);
Value of a = 0
Value of b = 1
Value of a = 0
Value of b = 2

Access Modifiers (Public, Private, Protected)

  • Public - can be accessed within and outside of class

  • Private - can only be accessed within the class

  • Protected - can be accessed by all classes in the package and all subclass outside of the package

public class example{
    int add(int a, int b){
         return a+b;
    }
}
public class Addition{
    protected int addTwo(int a, int b){
        return a+b;
    }
}
class Test extends Addition{
     public static void main(String args[]){
          Test obj = new Test();
     }
}
class outside{
    private int = 10;
    private int square(int a){ 
         return a*a;
 }
}
public class inside{
    public static void main(String args[]){
       outside obj. = new outside();
   }
}

Static Methods & Class Methods

  • part of the class, rather than each object (static properties and methods)

  • static methods do not require an object

  • static properties only have one instance, which is the same for all objects

this Keyword

  • allows you to access properties of the class
public class Main {
    int x;
  
    // Constructor with a parameter
    public Main(int x) {
      this.x = x;
    }
  
    // Call the constructor
    public static void main(String[] args) {
      Main myObj = new Main(5);
      System.out.println("Value of x = " + myObj.x);
    }
  }

  Main.main(null);
Value of x = 5

Main Method & Tester Method

  • used to test a class, is automatically called when class ran

  • usually creates an object and can test methods

  • mostly used as a tester method for classes

  • To execute the main portion of the code, a Main class with a main method is normally reserved which handles most of the executions of the code.

Inheritance & Extends

  • Inheritance: a way for attributes and methods to be inherited from one class to another

  • Extends: allows you to bring those attributes over from one class to another

Subclass Constructor, Super Keyword

  • subclass inherits all the members from the superclass
    • the constructor of the superclass can be invoked from the subclass
  • super keyword: refers to superclass objects
    • used to call superclass methods and to access the superclass constructor
// Super Class
public class Animal {

	private boolean vegetarian;

	private String eats;

	private int noOfLegs;

	public Animal(){}

	public Animal(boolean veg, String food, int legs){
		this.vegetarian = veg;
		this.eats = food;
		this.noOfLegs = legs;
	}

	public boolean isVegetarian() {
		return vegetarian;
	}

	public void setVegetarian(boolean vegetarian) {
		this.vegetarian = vegetarian;
	}

	public String getEats() {
		return eats;
	}

	public void setEats(String eats) {
		this.eats = eats;
	}

	public int getNoOfLegs() {
		return noOfLegs;
	}

	public void setNoOfLegs(int noOfLegs) {
		this.noOfLegs = noOfLegs;
	}

}
// SubClass
public class Cat extends Animal{

	private String color;

	public Cat(boolean veg, String food, int legs) {
		super(veg, food, legs);
		this.color="White";
	}

	public Cat(boolean veg, String food, int legs, String color){
		super(veg, food, legs);
		this.color=color;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

}

Overloading a method

  • same name, different parameters

  • a feature in java, which allows a class to have more than one method with the same name

  • ideal when you want to have two methods that essentially do the same thing

class CalculateSquare
 { 
public void square()
 { 
System.out.println("No Parameter Method Called");
 } 
public int square( int number )
 {
int square = number * number;
System.out.println("Method with Integer Argument Called:"+square); 
}
public float square( float number ) 
{
 float square = number * number;
 System.out.println("Method with float Argument Called:"+square); 
}
public static void main(String[] args)
  {
    CalculateSquare obj = new CalculateSquare();
    obj.square();
    obj.square(5);   
    obj.square(2.5);   
  }
 }

Overriding a method

  • same signature of a method

  • occurs when a subclass has the same method as the parent class

  • subclass provides a particular implementation of a method declared by one of its parent classes

// A Simple Java program to demonstrate
// Overriding and Access-Modifiers
  
class Parent {
    // private methods are not overridden
    private void m1()
    {
        System.out.println("From parent m1()");
    }
  
    protected void m2()
    {
        System.out.println("From parent m2()");
    }
}
  
class Child extends Parent {
    // new m1() method
    // unique to Child class
    private void m1()
    {
        System.out.println("From child m1()");
    }
  
    // overriding method
    // with more accessibility
    @Override
    public void m2()
    {
        System.out.println("From child m2()");
    }
}
  
// Driver class
class Main {
    public static void main(String[] args)
    {
        Parent obj1 = new Parent();
        obj1.m2();
        Parent obj2 = new Child();
        obj2.m2();
    }
}

Abstract Class & Abstract Method

  • abstract class: cannot be instantiated, but can be subclassed
  • abstract method: a method that has just the method definition, but does not contain implementation
abstract class Animal {
    public abstract void animalSound();
    public void sleep() {
      System.out.println("Zzz");
    }
  }

Standard Methods

  • blocks of code that can be called from another location in the program or class

  • toString(): returns the given value in string format

  • equals(): compares two strings, true if equal

  • hashCode(): returns an integer value generated by a hashing algorithm

Late Binding of an Object

  • referencing superclass object
    • ie Animal a = new Chicken(); Animal b = new Goat();
  • the compiler should perform no argument checks and no type checks on a method class
    • should leave it all to the runtime
// dynamic binding

class Animal{  
    void eat(){System.out.println("animal is eating...");}  
   }  
     
   class Dog extends Animal{  
    void eat(){System.out.println("dog is eating...");}  
     
    public static void main(String args[]){  
     Animal a=new Dog();  
     a.eat();  
    }  
   }

Polymorphism

  • any of overloading, overriding, late binding

  • the ability of a class to provide different implementations of a method

  • allows the ability to perform one thing in a variety of formats

class Animal {
    public void animalSound() {
      System.out.println("The animal makes a sound");
    }
  }
  
  class Pig extends Animal {
    public void animalSound() {
      System.out.println("The pig says: wee wee");
    }
  }
  
  class Dog extends Animal {
    public void animalSound() {
      System.out.println("The dog says: bow wow");
    }
  }

Big O notation

  • for Hash map, Binary Search, Single loop, Nested Loop

  • describes the set of algorithms that run worse, better, or at a certain given speed

  • represents the number of operations performed