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

OOP Classes

Summary of Java Classes OOP

Uploaded by

Samuel Themba
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)
22 views

OOP Classes

Summary of Java Classes OOP

Uploaded by

Samuel Themba
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/ 15

**This style of describing types of object will often be used in the course.

A specification gives:
• The name of the class (type) of object and a brief description of what the objects represent.
(**Class name.)

• A description of constructors, the ways of creating instances of the type of object. (**Data
about the object or what it can have.)

• A description of methods, the ways of manipulating instances of the type of object.(**Actions of


the object.)

**The automobile example:

Class Name: Automobile


Constructor/Data:
amount of fuel_______
speed_______
license plate_______
brand________
Methods(actions):
accelerate:
How:Press on the gas pedal
decelerate
How:Press on the brake pedal.

**object name: patsCar


amount of fuel: 10 liters
speed: 55 km/h
license plate: "135 XJK"
Brand: Mercedes

**object name: samCar


amount of fuel: 50 liters
speed: 180km/h
license plate: "1 GOAT"
Brand: Bugatti

// Objects which are instantious of the class automobile.


** A generic class has no data that is numbers and strings, only individual objects have data
and take certain actions that the class specifies they must.

** Objects of the same class have the same methods

**UML (Universal Modelling Language) CLASS DIAGRAM

Automobile <--------------------Class name


fuel: double
speed: double <----------------- Data/Constructors
license: String
accelerate(double pedalPressure): void
decelerate(double pedalPressure): void <----------- Methods

**SHORT RECAP

// The name of the file should begin with The name of the class and end with .java (file
extension)
// So if you write a definition of the class Automobile , it should be in a file named
Automobile.java.
// You can compile a Java class before you have a program in which to use it.
The compiled byte code will have the same name as the class, but ending with .class rather
than .java
// Compiling the file Automobile.java will create a file called Automobile.class.

**SIMPLE DEFINITION OF (Dog Class)

public class Dog


{ // Using public for the following instance viariables means there
are no restrictions on how we can use the viariables of which is
a bad idea.

public String name;


public String breed; <------------------------Data/constructors
public int age;

public void writeOutput() <--------------------Method1


{ // Action method
//outputs the data stored about the dog
System.out.println("Name: " + name);
System.out.println("Breed: " + breed);
System.out.println("Age in calendar years: " + age);
System.out.println("Age in human years: " +
getAgeInHumanYears()); System.out.println();
}
public int getAgeInHumanYears()
{ // Return value method
int humanAge = 0;
if (age <= 2)
{
humanAge = age*11;
}
else
{
humanAge = 22 +((age-2)*5);
}
return humanAge
}
}

**Using the Dog Class and its Methods

public class DogDemo


{
public static void main(String[] args)
{
Dog balto = new Dog(); // creates an object of type Dog that does
not take any arguements
balto.name = "Balto"; // balto.name is a variable of type string
balto.age = 8;
balto.breed = "Siberian Husky";
balto.writeOutput();

Dog scooby = new Dog();


scooby.name = "Scooby";
scooby.age = 42;
scooby.breed = "Great Dane";

System.out.println(scooby.name + " is a " + scooby.breed + ".");


System.out.print("He is " + scooby.age + " years old, or ");
int humanYears = scooby.getAgeInHumanYears();
System.out.println(humanYears + " in human years.");
}

**Why do we need new?

IN java new is unary operator used to create objects of a class.


e.g.
Dog scooby = new Dog();
it creates an object of the class Dog.The new operator then returns the
memory of the object.The object can have variables inside it namely instance
variables.

**Local Variables

A variable defined within one method is local to that method, meaning that if it happens
that there is another variable with the same name but in a different method it does not
change the first variable, this simply because in java variables have memory locations.
This is true whether the variables are in the same class or file.
we have discussed two types of variables -
1. instance variables whose meaning is confined to an object of a class.
2. local variables whose meaning is confined within a method definition.
**Global variable:
Java does not have a global variable rather it has a ==(static variable) that behaves the
same as a global variable.

**Block

Any local variable declared between a set of curly braces is local to that scope, meaning it
cannot be used anywhere else.

**Parameters of a primitive type

% Parameters have a data type.


% You can have more than one parameter in a formal definition.
e.g.
public void doStuff(int n1, int n2, double cost, char code)

% Parameters of a class type differ from those of primitive types.

**Information Hiding and Encapsulation


% Building a method without any need to understand the finer details of the method is called
information hiding.
% ENCAPSULATION: is the process of hiding all the details of a class definition that are not
necessary to understanding how objects of the class are used.
% A good method must have preconditions and post-conditions

**The public and private Modifiers

%instance variables should always be private.


%Private instance variables are accessible by name only within their own class

**Mutator and accessor methods

%We start the names of accessor methods with (get)


%We start the names of mutator methods with (set)

Methods Calling methods

% We can call methods within other methods without any receiving object

**A well Encapsulated Class

Implementation:
Private instance variables
Private constants
Private methods
Bodies of public methods
Interface:
Comments
Headings of public methods
Public named constants
Programmer who uses the class

1. Declare all instance variables as private


2. Include public accessor methods and private mutator methods where necessary.
3. Place a comment before each public method heading that fully specifies how to use the
class.
4. Make any helping methods private
5. Write comments within the class definition to describe implementation details.

% Application programming interface(API is the same thing as the class interface for the class.
% A well-encapsulated class definition is one where the internal data(instance variables) and
implementation are hidden from external code, and access to these details is controlled through
public methods

% Method should only be private if it is a helper method.

% anything that is private cannot be part of the class interface(the external code)

% The body of the method definition is not part of the class interface, only the name can be
used, and the underlying code is hidden in process called abstraction.

**Objects and References

% Variables of the class type(e.g. type: String) can name variables

% When declaring variables of a primitive type the data value is stored in the memory location
assigned to the variable

% When declaring variables of the class type the the object itself is not stored in the variable
but rather the memory address of the object is assigned to the variable. The object itself is
stored in some other location called **reference.

The address of this other location is called reference to the object. Thus class types are
often called reference types.
Reference types are are types whose variables hold references(memory locations) as
opposed to actual values of objects.

% Variables of primitive types have a fixed size

% Variables of a class type(e.g. String) can have varying sizes thus cannot be stored like
variables of a primitive type.

% All class types are reference types but not all reference types are class types.

**Defining an Equals method for a class

public boolean equals(Species otherObject)


{
return (this.name.equalsIgnoreCase(otherObject.name)) &&
(this.population == otherObject.population) &&
(this.growthRate == otherObject.growthRate);
}
// Equals method is of the class String.
% Naming boolean valued methods: e.g.
if (s1.isExtinct())
// In English means if s1is extinct.
// Beginning a boolean valued method with is or has clarifies the method for others.

% **Call by reference parameter passing: parameters of a class type

% Parameters of a class type, Formal parameters hold the memory address of the location of
objects of the class type.

% **Differences between Primitive-types and Class-types parameters

% An object passed as an argument can be changed by a method.But the same


object cannot bereplaced by another object.
% A method cannot change the value of an argument of a
primitive type.

Read the summaries in the book from the most difficult sessions.

**Constructors

% A special method : Constructers creates and initialize new objects.


% The default constructor is called a no argument constructor does not have any parameters.
% You need to initialize instance variables once you define them.
% A constructor is a method that is called when an object of the class is created by using the
new operator.
% Constructors can have other private methods within them in the same class
% Calling a Constructor from other Constructors
We use the keyword (this) to invoke the first constructor in our second constructor in the same
class.

public class Pet3


{
private String name;
private int age; //in years
private double weight;//in pounds
public Pet3(String initialName, int initialAge, double initialWeight){
set(initialName, initialAge, initialWeight);
}
public Pet3(String initialName) {
this(initialName, 0, 0);
}
public Pet3(int initialAge) {
this("No name yet.", initialAge, 0);
}
public Pet3(double initialWeight) {
this("No name yet.", 0, initialWeight);
}
public Pet3( ) {
this("No name yet.", 0, 0);
}

**Static Variables and Static Methods

% Static variables and static methods belong to a class as a whole and not to an object of a
class.

% static variables(class variables)


public static final double FEET_PER_YARD = 3;

// Only on e copy of feet_per_yard exists.


// Individual objects thus share this constant.
// Keyword (final) means the constant cannot change in value
// However we can have static methods that change that is if we
ommit the keyword (final).
// just like instance variables static variables can be private and public
also if they are not constants they should be private.
// System.out -- out is a static variable of the class System inthe
PrintStream package.

%static methods()
public static double convertInchesToFeet(double inches) {
return inches / INCHES_PER_FOOT;
}
// We call a static method using the class name. that method
// A non static method can reference a static variable and instance variable
// A static method can reference a static variable/static method but not an instance variable/non-
static method unless it has an object to do so other than the keyword(this) as its calling object
meaning it does not have a separate object other than the class itself.
// Main is a static method.

%You can add a main method in a class to test other methods


import java.util.Scanner;
public class Species {
private String name;
private int population;
private double growthRate;

public static void main(String[] args) {


Species speciesToday = new Species( );
System.out.println("Enter data on today's species:");
speciesToday.readInput( );
speciesToday.writeOutput( );
System.out.println("Enter number of years to project:");
Scanner keyboard = new Scanner(System.in);
int numberOfYears = keyboard.nextInt( );
int futurePopulation = speciesToday.predictPopulation(numberOfYears);
System.out.println("In " + numberOfYears + " years the population
will
be " + futurePopulation); speciesToday.setSpecies("Klingon
ox",10,15);
System.out.println("The new species is:");
speciesToday.writeOutput();
}
}

**The Math class

% Contains a collection of static methods and variables


Math.round() --- 3.56 --> 4 // rounds to the nearest whole number
Math.floor() ---- 3.9 --> 3 // rounds down --- the floor
Math.ceil() --- 3.1 --> 4 // rounds up --- the ceiling

**Static Methods in Class Math

Name Description Argument Return type Exmple Value


type returned
pow Power double double Math.pow(2.0,3.0) 8.0
abs Absolute int, long, Same as the Math.abs(–7) 7 ;7 ;3.5
value oat, or type of the Math.abs(7)
double argument Math.abs(–3.5)
Name Description Argument Return type Exmple Value
type returned
max Maximum int, long, Same as the Math.max(5, 6) 6; 5.5
float, or type of the Math.max(5.5, 5.3)
double arguments
min Minimum int, long, Same as the Math.min(5, 6) 5; 5.3
float, or type of the Math.min(5.5, 5.3)
double arguments
random Random none double Math.random() Random
number number in
the range ≥
0 and < 1
round Rounding float or int or long, Math.round(6.2) 6; 7
double respectively Math.round(6.8)
ceil Ceiling double double Math.ceil(3.2) 4.0 ; 4.0
Math.ceil(3.9)
floor Floor double double Math.oor(3.2) 3.0 ; 3.0
Math.oor(3.9)
sqrt Square root double double Math.sqrt(4.0)

The random method:


returns a double that is 0 <= x < 1.
Often a number between 0 and 1 is not desired thus we can scale
to the desired range and type casting is necessary.

e.g. int die = (int)(6.0 * Math.random()) + 1;


Multiplying the random number by 6.0 gives us a value in the range ≥ 0 and <
6.0. Type casting this to an int truncates the result, which is an integer
that is 0, 1, 2, 3, 4, or 5. Adding 1 results in a random integer that is in
the range 1–6.

%The value returned by Math.min(n1, n2) will be of type long because when two numeric
values of different types are compared, Java promotes the smaller type ( int ) to the larger type
( long ) before performing the comparison.

**Wrapper Classes

% A wrapper class in Java is an object that "wraps" or encapsulates a primitive data type (like
int, char, double) in an object so that it can be treated like any other object. This provides extra
functionality and allows primitives to be used in contexts where only objects are allowed.
**Primitive Data Types vs. Wrapper Classes

Primitive Type Wrapper Class


int Integer
char Character
double Double
float Float
long Long
short Short
byte Byte
boolean Boolean

**Why use wrapper classes?

1. Working with collections: Javas collection classes (like ArrayList, HashSet, etc.) can only
work with objects , not primitive types. So if you need to store integers you cannot store
(int) directly , but you can store an Integer (a wrapper class).

ArrayList<Integer> numbers = new ArrayList<>();


numbers.add(5); // Auto

2. Methods that require objects: some methods only want objects not primitives and wrapper
classes allow for this.
3. Utility Methods: Wrapper classes provide useful methods . Like for example Integer class
has methods like Integer.parseInt() to convert strings to integers.

**Autoboxing and Unboxing

Autoboxing: Automatically converts primitive to its corresponding wrapper class

int a = 10;
Integer obj = a; // int to Integer object(primitive to object) // This i
just an abbreviahtion for creating an intger obj
Integer obj = new Integer)

Unboxing: Automatically converts wrapper class to corresponding primitive type


Integer obj = 20;
int b = obj; // Integer object to primitive type int
// This is just an abbreviahtion for reversing a wrapper class to a
primitive type
// int b = obj.intValue;

% It is always a good idea to use the trim() method to avoid any trailing white space when using
the parseInt method
Double.parseDouble(theString.trim())

% We can also go back using toString method: Integer.toString(42); returns "42"

% Wrapper classes have no default constructor:


Thus the statement such as:
Integer n = new Integer(); //Invalid!
% They do not have set methods

**Overloading

Overloading the method name means giving the same name to more than one method in
the same class.
By doing this you must ensure that the methods have different parameters

public class Overload {

public static void main(String[] args) {


double average1 = Overload.getAverage(40.0, 50.0);
double average2 = Overload.getAverage(1.0, 2.0, 3.0);
char average3 = Overload.getAverage('a', 'c');
System.out.println("average1 = " + average1);
System.out.println("average2 = " + average2);
System.out.println("average3 = " + average3);
}
public static double getAverage(double first, double second) {
return (first + second) / 2.0;
}

public static double getAverage(double first, double second,


doublethird){
return (first + second + third) / 3.0;
}
public static char getAverage(char first, char second) {
return (char)(((int)first + (int)second) / 2);
}
}

% You can also overload constructors

% You cannot have methods with the same name and same parameters but different return
types(You can overload on the basis of return type).

**Privacy leak

A private instance variable having a class type could be changed outside of the class.
To avoid this we should use the class type without mutator methods e.g.(String class has
no accessor methods)
Or primitive types to name instance variables.

To avoid the problem of returning an object that could be modified externally (and therefore
altering the internal state of the PetPair class), you should create separate accessor methods
for each property of the pet (name, age, and weight). These methods will return only specific
pieces of data rather than returning the entire object.

Here are the three accessor methods you can define to retrieve the pet's name, age, and
weight without exposing the full object:

`public class PetPair {


private Pet first;
private Pet second;

// Other methods and constructors...

// Accessor method to get the name of the first pet


public String getFirstPetName() {
return first.getName();
}

// Accessor method to get the age of the first pet


public int getFirstPetAge() {
return first.getAge();
}
// Accessor method to get the weight of the first pet
public double getFirstPetWeight() {
return first.getWeight();
}

}`

Explanation:
1. getFirstPetName(): This method returns the name of the first pet, using the getName()
method of the Pet class.
2. getFirstPetAge(): This method returns the age of the first pet, using the getAge()
method of the Pet class.
3. getFirstPetWeight(): This method returns the weight of the first pet, using the
getWeight() method of the Pet class.

By splitting the accessors in this way, you avoid returning the full Pet object, preventing the
caller from modifying the internal state of the PetPair class indirectly through mutator methods
like setName() , setAge() , or setWeight() .

**ENUMERATION AS A CLASS

The compiler creates a class when it encounters an enumeration.

enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES}

The compiler creates a Suit class. The enumerated values are names of public static objects
whose type is Suit. Referenced in this format:

Suit s = Suit.DIAMONDS; // REMEMBER DIAMONDS is a name of public staic object

The class has methods: equals, compareTo, ordinal, toString, and valueOf.

s.equals(Suit.HEARTS) // returns false


s.compareTo(Suit.HEARTS) // checks if s is before HEARTS or after HEART and returns
an integer that is negative, zero or positive. in this case returns a negative integer
s.ordinal( ) // returns position of DIAMONDS in the enumeration -- 1
s.toString( ) // returns the name of its invoking object as a string
Suit.valueOf("HEARTS") returns the object Suit.HEARTS.

**Packages

A package is a collection of Classes grouped together into a folder


The name of the folder is name of the package.
If general.utilities is the name of the package, then each of the files in the package would
have the following statement at the start of the file.

package general.utilities;

I f we want to import the class HelpfulClass from the package general.utilities we would
say

import general.utilities.HelpfulClass;

.......

You might also like