Lecture 2 and 3 objects Flashcards
What do objects do?
Objects allow us to bring together related variables and methods into a single thing.
eg a Scanner object.
What are objects defined by?
Objects are defined by a class. Classes do not always need to include the main method. In general classes have:
1) a name (starting with a capital letter)
2) some variables (known as class attributes)
3) methods
4) some special methods, called constructors
If you don’t create a constructor, the system will create one for you with no arguments.
Each class is defined in its own specific file
How do we use a class that we create?
We have to create another class to call it
How do you create a new object? What is the general format if a class already exists?
= new (input1, input2);
input1 and input2 are the arguments passed to the constructor.
From there, you can call methods within the class by: .();
You can change the value of the attributes in a class, from another class, by:
. = ;
How can you tell if a method is a constructor by looking at it?
There are two main tell-tales.
The name of the constructor is the same as the name of the class and there is no return type.
e.g. public Circle(double r){
radius = r;
}
What does “private” mean?
These classes, attributes, and methods can only be used by the class in which they are defined.
What does “protected” mean when defining a class?
These classes, attributes and methods can be used only by other classes in the same package or that inherit from this class
What are getter and setter methods?
These are public methods that allow other programmers to access the class and change variables, when the class attributes are private.
Why is it a convention to make the class attributes private?
The person who created the class has control over other people accessing and modifying the variables.
Can you generate getters and setters in Eclipse?
In eclipse, you can do:
Source –> generate getters and setters
Why do we use “this”?
e.g this.radius = radius
Often the arguments to a method are named the same as the class attributes, but these are not the same thing. If we say this.radius, we are saying that the radius is the class attribute (not the input argument to our constructor). Using “this” avoids ambiguity.
Similar to “Self” in Python.
What does static mean?
Static is an optional keyword that can be used to create variables or methods that will exist independently of any instances created for the class.
Therefore, they can be accessed without creating an instance of the class (i.e. an object).
What’s another word for decorator?
modifier
Why is the main method static?
It involves creating objects from other classes and isn’t applied to an object itself.
What is the reference of an object?
You can think of references like the “address” of a “house”
We can have many references going to the same object.
A single reference can only refer to one object.