CS2312 Lecture 2
Objects and Classes
Objects-Oriented Programming
- Programming using objects
- An object represents an entity in the real world
- Objects have two parts:
- State: Properties of an object.
- Also referred to as field or attributes
- Behavior: Things the object can do.
- Also referred to as methods or functions
- State: Properties of an object.
Why use objects?
- Modularity: Once we define an object, we can reuse it for other applications.
- Encapsulation: Programmers don’t need to know exactly how the object works. Just the interface. (Abstraction)
The keyword class tells java that we’re defining a new type of Object.
Classes are a blueprint.
Objects are instances of classes.
Nearly everything in Java (except primitives and arrays) are Objects and have a Class.
The this keyword means this particular object. Objects know themselves
The new keyword creates a new object. new must be followed by a constructor
Constructor
Constructors provide objects with the data they need to initialize themselves, like “How to Assemble” instructions.
Constructor name is same as the class name
No return type – never returns anything
Usually initialize fields
We can define constructors to take any number of arguments.
All classes need at least one constructor
Example:
Defind a class
public class Baby{ String name; double weighr = 5.0; boolean isMale; int numPoops = 0; Baby[] siblings; void sayHi(){...} void eat(double foodWeight){...} }
Using classes
Baby shiloh = new Baby("Shiloh", true); shiloh.sayHi(); shiloh.eat(1.0)
Static types and methods
static
- Applies to fields and methods (Share fields and methods to all instances)
- Means the field/method
- Is defined for the class declaration,
- Is not unique for each instance
static field
- A given class will only have one copy of each of its static fields
- This will be shared among all the objects.
- Each static field exists even if no objects
- of the class have been created.
- Use the word static to declare a static field.
- Only one instance of a static field data for the entire class, not one per instance.
static/class methods
- Static methods are shared by all objects of the class
- One copy for all objects
But, Have access only to static fields and methods of the class (Cannot access non-static ones)
Example
public class Baby{ static int numBabiesCreated = 0; String name; int age; ... public int getAge(){ return age; } public static Baby older(Baby b1, Baby b2){ if(b1.getAge() > b2.getAge()) return b1; return b2; } }
We HAVE TO use the static key word on the main method in the class that starts the program
-No objects exist yet for the main method to operate on