Classes and Objects
Difference between classes and objects
Object is an instance of a class. That means an object belongs in a class.
Class provides a template for something more specific that the programmer
has to define. (Special (main method) and regular classes (no main method))
Variables are properties, methods are actions.
Encapsulation in Java is a mechanism of wrapping the data (variables) and
code acting on the data (methods) together as single unit. Variables are
private and there should be public getter and setter methods.
Class variables and methods. Teach them how to create variables and
methods in a class.
Class instantiation. Teach them how to instantiate an object. Instantiation
is creating an object.
Creating your own class
Defining your own class
<modifier> class <name>{
<attributes>
<constructor>//allows you to initialize variables as soon as you create an
object.
//its like a method with the same name as your class
<methods>
}
Declaring Attributes
Instance variables are variables that can be used throughout the whole
class. Can be used by any method inside and outside the class, if they are
public.
Static variable or class variable is a variable that is the same for all the
objects of the same class. Static variable and method belongs to a class but
doesnt need an object to be called because it is a class variable.
Casting, Converting and Comparing Objects
Casting
Casting is converting. We are converting variables and objects and data
types. Converting information to a new form is called casting and casting
produces a new value that is a different type of variable object. Only data
type that cant be casted is boolean.
Variable to variable example:
Variable to variable
i.e.
double source=150.05;
int dest=(int)source;
Object to a variable
Declare an object: Integer wholeNumber=new Integer(500); int
newVal=wholeNumber.intValue(); //sop is 500
Implicit Casting conversion that java automatically initiates. Implied
though not plainly expressed.
Int a=5;
Double xy=a;
Explicit Casting is seeing completely see what we are doing. The format is
usually (dataType)value where dataType is the value you are converting to
and the value is an expression that results in the value of the source type.