Basic Java Concepts




  • Basic Java Concepts


  • Java Chapter Basic Summary
    • A class should represent a single concept from the problem domain, such as business, science, or mathematics.
    • The public interface of a class is cohesive if all of its features are related to the concept that the class represents.
    • A class depends on another class if it uses objects of that class.
    • It is a good practice to minimize the coupling/dependency between classes.
    • An immutable class has no mutator methods.
    • A side effect of a method is any externally observable data modification.
    • You should minimize side effects that go beyond modification of the implicit parameter.
    • In Java, a method can never change parameters of primitive type.
    • In Java, a method can change the state of an object reference parameter, but it cannot replace the object reference with another.
    • A precondition is a requirement that the caller of a method must meet. If a method is called in violation of a precondition, the method is not responsible for computing the correct result.
    • An assertion is a logical condition in a program that you believe to be true.
    • If a method has been called in accordance with its preconditions, then it must ensure that its post-conditions are valid.
    • A static method is not invoked on an object.
    • A static field belongs to the class, not to any object of the class.
    • The scope of a variable is the region of a program in which the variable can be accessed.
    • The scope of a local variable cannot contain the definition of another variable with the same name.
    • A qualified name is prefixed by its class name or by an object reference, such as Math.sqrt or other.balance.
    • An unqualified instance field or method name refers to the 'this' parameter.
    • A local variable can shadow a field with the same name. You can access the shadowed field name by qualifying it with the 'this' reference'.
    • A package is a set of related classes.
    • The 'import' directive lets you refer to a class of a package by its class name, without the package prefix.
    • Use a domain name in reverse to construct unambiguous package names.
    • The path of a class file must match its package name.
    • Unit test frameworks simplify the task of writing classes that contain many test cases. The JUnit philosophy is to run all tests whenever you change your code.
    • Mutator methods modify the object on which it is invoked
    • Accessor method accesses info without making any mods.
    • Always get the same answer, unlimited, and state of object does not change.
    • Immutable methods have only accessor and not mutator
    • Safe to give out references to its objects freely
    • Once a string is constructed, its contents never change.

Java Variables, Instantiation, Arrays

Instantiation
BankAccount myAccount = new BankAccount (20202, "fred", 100.00)
  • Memory that contains the instance date for myAccount
  • Also contains references to methods defined for objects of this class
  • Java requests dynamic memory when NEW is Called 
Valued Meethods return a single value, and should be used in an expression
  • Returns a value (primitive type) 
  1. Void methods – no return
  2. Arguments are associated in order with formal parameters
  3. Formal parameter in the method becomes an alias for the argument passed to it, treated as a local variable

  4. Formal parameter is discarded when method terminates
    Pass by value
    1. For primitive type, parameter is initialized to value of argument in call

  5. Pass by reference
    1. For a class type, formal parameter is initialized to the address of the object in the call
Garbage memory – removed if not being used by JVM
Mutator method – setter method – changeable parameters

 
Default value of every VALUE in ARRAY is NULL!

  • Arrays
    • They are data structures
    • Contain primitive or objects
    • Ex – data[0] represents a element in a allocated spot
    • Data.length – gives the length of the array
    • They have fixed length
    • Arrays are always passed by reference

  • Partially filled arrays
    • Array length = max number of elements in array
    • Usually it is partially filed
    • Do not overfill the array or Indexoutofboundsexception will be thrown

    • Resize array if underestimated size
      • Must make new array
      • Copy old elements to new array

    • Resizing is bad
      • Takes time, memory
      • Bad because have to copy over array

 
Designing Class
  • Nouns are classes
  • Verbs are methods

  • Cohesion
    • Represent single concept
    • Public interface of class is cohesive
Post Conditions
  • Condition that is true after a method has completed
  • Return something if the program fulfills its code 
Project 1
  • Create DiceTester
  • Gets user input (n)

  • Repeats
    • RunTest(n)
    • Report()

  • Until user chooses to quit
    • Note:
      userinterface is developed in lab 2

  • DiceTester

    • Constructor
      • Sets up arrays for counters

    • RunTest()
      • Generates and counts dice rolls

    • Report()
      • Analyzes counter arrays
  • User Interface
Interface:
  • A interface is a formal contract
  • If called, need to implement all methods or program will not compile
  • Contain public constants, signatures for public methods, comments
  • Interface type is similar to a class, but many different differences:

  • INTERFACES
    • All methods in Interface are ABSTRACT

    • All methods are automatically public
      • Public modified not needed
    • Interface type does not have instance fields

    • Ex:

      • Public interface doable {
        MAX = 100;
        Void doThis();
        Int doThat();
        Void doThis (float value, char ch);
        Boolead done (int num);

 
}

 
  • Interface cannot be instantiated
  • Multiple classes can implement same interface
  • A class can implement more than one interface

  • An interface can be used as a data type"

    • Public void someMethod ( someInterface x){
      }


  • in any class that implements an interface:
    • methods return type or parameter type may be Object

    • a type case would probably be needed within that method


      public class CanDo implements Doable{

      public void doThis(){
              // code you want to put in
      }

       
      Publick int doThat(){
              // code that you want to put in
      }

       
      …… and other methods in DoAble Interface.


      }


  • Comparable Interface
    • compareTo method returns 0, positive, negative number. If positive then first object is greater than second. Negative number means first object is less than second. If 0 then both equal
    • up to the coder to determine what makes a object less greater or equal

  • Interfaces and Polymorphism

    • Interfaces
      • Contract. Need to implement methods no matter what
      • Specifies operations that must be implemented

Public class DebtList
{
    Private debt[] mydebts;
Private int count;

 
Public debtList (int size)
{
Count = 0
myDebts = new Debt[size];
    }

 
public void addSorted (Debt d)
{
int k = 0;

 
while (K<count && d.greaterThan(myDebts[k]))
            k++;
   
for (int j=count; j>k; j--)
            mydebts[j] = mydebts[j-1];

 
myDebts[k] = d;
count++;
}
  • Interface creates a contract – if you call it then ALL methods need to be implemented

  • How to use Class:


    GenericList debtList = new GenericList(10);

    GenericList shapeList = new GenericList(10);


     
    Debtlist.addSorted (new debt(5000.00 , 327.51, 0.055 ) );
    debtList.addSorted ( new debt (2000, 200, 0.06) );

 
        shapeList.addSorted ( new circiel (3.0) );
        shapeList.addSorted ( new square (7.1) ) ;

  • Nothing stopping from putting Shape in Debt or Debt in Shape
    • debtList.addSorted ( new circle (3.0 )); //No error but wrong
  • if ( p instance of Debt)

  • Packages
    • Set of related classes

    • To put classes into a package, you must place a line:
      • Package packageName;

Computer Science – Polymorphism and Inheritance

 
 

Inheritance

  • Reusable code, maintain the code easier
  • Implemented by using 'extend' keyword
  • Hierarchy of classes
    • Parent, grandparent, ancestor (super)
    • Child, grandchild, descendant
    • Inheritance uses parent etc
    • Models a IS A relationship
    • Child class inherits the methods defined in parent class
    • Private data fields in parent class are not accessible by name only
      • Need getters and setters
    • Private methods are NOT available
    • Methods in child class OVERRIDES same method in parent class with same name
    • Overriding
      • Child class has same method with same signature as method in Parent class
        • Same name
        • Same type
        • Same return, order of parameters, just all same
      • If same method in class B and same class with same parameters in class A, then the class B method is run!
        • Unless a SUPER call is put inside the class B method
      • To prevent a override -
        • Use FINAL in parent class
      • Rules on Inheritance
        • Child classes may NOT remove attributes (instance fields) or methods
        • Public parent methods cannot override private child class methods
        • Multiple inheritance not supported in Java
        • Parent (base) class cannot inherit from child class
        • Every class automatically inherits from OBJECT
      • Derived Classes can
        • Inherit method
        • Override method
          • Supply a different public implementation of a method that exists in the base class
        • Overload method
          • Supply a method with the same name as method that exists in the base class BUT change the signature!
        • Add method
      • Derived classes can
        • Inherit field: all friends from superclass are automatically inherited, even though they might not be visible
        • Add field: supply new field that does not exist in base class

           
           

           
           

Powered by Blogger