0% found this document useful (0 votes)
8 views

CS1122___Week_2___Objects_and_Classes

This document outlines the basics of classes and objects in Java, emphasizing the creation of classes, the distinction between classes and objects, and the importance of encapsulation. Key concepts include constructors, instance variables, non-static methods, access modifiers, and the use of getters and setters. It also highlights best practices for object-oriented programming and the significance of public interfaces in maintaining encapsulation.

Uploaded by

jdbranch
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

CS1122___Week_2___Objects_and_Classes

This document outlines the basics of classes and objects in Java, emphasizing the creation of classes, the distinction between classes and objects, and the importance of encapsulation. Key concepts include constructors, instance variables, non-static methods, access modifiers, and the use of getters and setters. It also highlights best practices for object-oriented programming and the significance of public interfaces in maintaining encapsulation.

Uploaded by

jdbranch
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Week 2 - Classes and Objects

Week 2 - Classes and Objects - Basics 1 29


Goals for the Week

By the end we should be able to:


▶ Create a class in Java and determine the difference between a
class and an object

▶ Identify different aspects of a class, including constructors,


instance variables/methods, and static variables/methods,
access modifiers, and getters/setters

▶ Explain the two major aspects of how to achieve proper


encapsulation and describe how access modifiers can be used
to achieve these.

Week 2 - Classes and Objects - Basics 2 29


Classes

▶ We worked pretty heavily with classes beforehand in CS1121.

▶ Java coding guidelines suggest these are named starting with a


capital letter and being camel cased (Pascal Cased).
▶ All code in java is placed in a class!
▶ public static void main(String[] args)
▶ public static void main(String args[])

▶ As we recall, the syntax for this is pretty straightforward:

public class Example {


// Methods and data here
}

Week 2 - Classes and Objects - Basics 3 29


Static methods and variables
▶ Methods that have the static keyword in front of then exist as
part of a class.
▶ They can be accessed without the need to make a new object
first.
▶ Unlike non-static methods, which are tied to objects, they don’t
save a state between calls.

▶ Similarly, we’ve worked primarily with variables that have the


scope of a method or loop.

▶ While static variables (called class variables) do exist, such as


Math.PI, these are fairly rare.

▶ Static methods and variables are used by classes.

▶ So why do we need non-static stuff?

Week 2 - Classes and Objects - Basics 4 29


What is an object, and how is it different than a
class?

▶ A class is a blueprint for objects with similar behavior.

▶ When you make a new object with a class, the data type of that
object is the class name.

▶ We need objects because they store data, and contain methods


that act upon that data.

▶ When we use the new keyword, we make an instance of an


object!

Week 2 - Classes and Objects - Basics 5 29


We’ve made Objects already!

// This creates a new object ! It stores info ,


// like where it reads in from , how much
it ’s read , etc . ,
// and has accompanying methods
Scanner input = new Scanner ( System . in ) ;

// We can also declare and use our own


objects !
MySpecialObject example = new
MySpecialObject () ;

Week 2 - Classes and Objects - Basics 6 29


What’s New for Objects

▶ A Constructor

▶ Non-static Methods

▶ Instance Variables

Week 2 - Classes and Objects - Basics 7 29


Constructors

▶ Constructors are a special method called at the start of an


object’s creation.

▶ Can be overloaded, just like a normal method.

▶ Is the same name as the class.

▶ Does not have a return type!

Week 2 - Classes and Objects - Basics 8 29


Non-static Methods

▶ Methods describe the behavior and actions an object can take.

▶ Lacks the static keyword we’ve been using in the past.

▶ This method can only be called with respect to an object.

▶ Most methods are marked as public.

▶ Otherwise, these methods are very similar to what we’ve


worked with before.

Week 2 - Classes and Objects - Basics 9 29


Method Declaration Example

▶ Methods always follow the same template:


1. An Access Modifier (who can use this method?)
2. Whether the method is static or not (we omit the word ”static” if it
is not static.)
3. Return Type (a data type of some kind)
4. Name (We need to be able to reference our defined method!)
5. Parameters (the arguments the method will need to run.

public static void main ( String [] args ) { ... }

private int myMethod ( int var1 , int var2 ) { ... }

public boolean isArrEvenLen ( Object [] myArr ) { ... }

Week 2 - Classes and Objects - Basics 10 29


Instance Variables
▶ Instance Variables describe the information an object holds.

▶ These are variables outside of methods that are not marked


with the static keyword.
▶ These should be marked as private. If you need to modify
them, use methods to do so.
▶ This is encapsulation in action!
▶ The methods are the public interface, and the private variables
are the implementation details!

▶ Methods can have variables with the same name as an


instance variable. We can disambiguate between the two using
the this keyword.
▶ The this keyword on it’s own refers to the object itself! You’re
totally allowed to do that!

Week 2 - Classes and Objects - Basics 11 29


Bringing it all together 1/2

public class Counter {


// This isn ’t in a method !
private int value ;

// A constructor !
public Counter () {
this . value = 0;
}

// I ’ ve overloaded it !
public Counter ( int value ) {
this . value = value ;
}

Week 2 - Classes and Objects - Basics 12 29


Bringing it all together 2/2

public int getVal () { // A getter


return value ;
}

public void incVal () { // A setter


value ++; // the same as value = value +1
}
}

Week 2 - Classes and Objects - Basics 13 29


Making and using an Object

▶ Using an object requires a specific syntax:


▶ <type> <name> = new <type>(<args>);

▶ So, if I wanted to make a new Counter object, I would type


Counter example = new Counter();

▶ The arguments in the parenthesis are the arguments provided


to our constructor.

Week 2 - Classes and Objects - Basics 14 29


Example use of an Object

public static void main ( String [] args ) {


// Here is one of our constructors .
Counter counter = new Counter () ;
// Here is the other one .
// Remember we overloaded it ?
Counter counter2 = new Counter (19) ;

counter . incVal () ;
System . out . println ( counter . getVal () ) ;
}

Week 2 - Classes and Objects - Basics 15 29


Example use of an Object

▶ Doesn’t this remind you of some other things you’ve used in


CS1121?
▶ Scanners
▶ Scanner input = new Scanner(System.in);
▶ ArrayLists
▶ ArrayList<Integer> myList = new
ArrayList<Integer>();

▶ These are objects that are made from a Scanner and


ArrayList class.

Week 2 - Classes and Objects - Basics 16 29


The Implicit Parameter: this

▶ When you want to refer to the object itself in a method, you use
the key word this.

▶ Since all non-static methods automatically get it, it is referred to


as the implicit parameter, since it is an argument that is
implied.

▶ You can visualize it as “this instance of an object”.

▶ You can provide the object itself as an arugment to a method,


or refer to our instance variables using this.VARIABLENAME.

Week 2 - Classes and Objects - Basics 17 29


Using the implicit parameter

public class Counter {


private int value ;

SomeObject ( int value ) {


// use this to refer to " this object "!
this . counter = counter ;
}
}

Week 2 - Classes and Objects - Basics 18 29


Encapsulation
▶ Encapsulation is the process of hiding implementation details
and providing an external public interface for people to use.
This allows your code to be easier to update, and to prevent
people from having to make assumptions about how you made
something work.
▶ This is rather important. This allows for you to update your code
without the fear of others using your code having to modify
theirs!
▶ A public interface is the set of methods through which our
objects can be manipulated.
▶ When we make a method public, we make it part of the public
interface!
▶ If we want a method only we can use, we might make it
private, like our variables, so it is not part of the public
interface!
Week 2 - Classes and Objects - Basics 19 29
Access Modifiers

▶ While typically, methods should be public and instance


variables private, there are times when you may need more
fine-grained control over what classes can see or access
certain variables.

▶ For this, we have access modifiers.

▶ Access modifiers use one of three keywords. These keywords


can be omitted, as well, for a fourth option.
▶ Private, Protected, Public

▶ The fourth option, a default one, is unique and different from


these access modifiers.

Week 2 - Classes and Objects - Basics 20 29


Scope of Access Modifiers

Week 2 - Classes and Objects - Basics 21 29


Getters and Setters

▶ Not all methods are the same.

▶ Some methods are meant to simply retrieve the value of an


instance variable.
▶ These are called getters or accessors.

▶ Some methods are designed to modify the values of instance


variables.
▶ These are called setters or mutators.

Week 2 - Classes and Objects - Basics 22 29


Example Getter and Setter

public class CoordinateX {


private double x = 0.0;

public void setX ( double value ) {


x = value ;
}

public int getX () {


return x ;
}
}

Week 2 - Classes and Objects - Basics 23 29


toString

▶ Not all methods are the same.

▶ A special method you can define is toString

▶ Whenever you try to print an object, this is implicitly called.

▶ If it isn’t defined, it returns the hash value based on the memory


location of the object.
▶ Hint: This isn’t useful.

▶ Instead, we can define our own toString method which returns


a String.

Week 2 - Classes and Objects - Basics 24 29


toString Example

public class Foo {


private String stored = " I printed
correctly ! " ;

public String toString () {


return stored ;
}

public static void main ( String [] args ) {


Foo bar = new Foo () ;
System . out . println ( bar ) ;
}
}

Week 2 - Classes and Objects - Basics 25 29


== and Objects
▶ == doesn’t work for objects (aside from Strings sometimes)

▶ When you compare two objects, use


object1.equals(object2) to determine if they are equal.
▶ You can test this by comparing two simple objects.
▶ Similarly, if you want to compare values, > and < don’t work.
Instead use compareTo.
▶ this is called with object1.compareTo(object2)
▶ compareTo returns an int < 0 if object1 < object2
▶ compareTo returns an int > 0 if object1 > object2
▶ compareTo returns 0 of object1 == object 2

▶ Similar to toString, we can override default functionality so that


our objects can use this.

Week 2 - Classes and Objects - Basics 26 29


null

▶ Before an object variable is initialized it has the value of null. If


your variable has this value, it has never been assigned a
corresponding object (or was assigned it for some reason).

▶ This can be useful for debugging. If an object has the value


null, it’s most likely not initialized.

▶ If you try to call a method on it or access a variable on a null


object, you will get a NullPointerException.

▶ It’s often worth checking if an object is not null before acting


on it if, for some reason, that is possible. This is probably the
only time == is used.

Week 2 - Classes and Objects - Basics 27 29


null

public static int getStringLength ( String myStr ) throws


I l le g a l A r g u m e n t E x ce p t i on {
if ( myStr == null ) {
// the object is null !
throw new I l l eg a l A ru g m e nt E x c ep t i o n ( " myStr
cannot be null " ) ;
}
return myStr . length () ;
}

Week 2 - Classes and Objects - Basics 28 29


Best Practices & Wrapup

▶ Don’t rely too much on static methods. While they can be


nice, in Object Oriented Programming, non-static methods are
usually more useful.

▶ Classes are the blueprints to make objects.

▶ Objects are data and the methods that are tied to that stored
data.

▶ Remember to use public interfaces to enforce encapsulation!

Week 2 - Classes and Objects - Basics 29 29

You might also like