W9-Presentation-Basic Java Object Oriented Programming
W9-Presentation-Basic Java Object Oriented Programming
Programming
Introduction to Object Oriented
Programming
- it revolves around the concept of objects as the basic
elements of your programs.
- it enables you to convert the value of one data from one type
to another primitive type.
char varChar = A;
int varInt = varInt; //implicit cast
System.out.println(varInt); //print 65
In case that we want to convert a data that has a large type to a
smaller type, we must use an explicit cast. Explicit casts take the following form:
(Data_Type)value;
Where,
Data_Type, is the output data type that you’re converting.
value, is an expression that results in the value of the source type.
For example,
double varDouble = 10.12;
Int varInt = (int)varDouble; //convert varDouble to int type
double x = 10.2;
Int y = 2;
int result = (int)(x/y); //typecast result of operation to int
Casting Primitive Types
To cast,
(Class_Name)object;
Where,
Class_Name, is the name of the destination class.
value, is a reference to the source object.
For example,
Two classes have names that differ from the corresponding data type:
Character is used for char variables.
CAUTION: The void class represents nothing in Java, so there's no reason it would
be used when translating between primitive values and objects. It's a placeholder
for the void keyword, which is used in method definitions to indicate that the method
does not return a value.
Comparing Objects
- The exceptions to this rule are the operators for equality: == (equal)
and != (not equal).
NOTE: Why can't you just use another literal when you change str2, rather than
using new? String literals are optimized in Java; if you create a string using a
literal and then use another literal with the same characters, Java knows enough
to give you the first String object back. Both strings are the same objects; you
have to go out of your way to create two separate objects.
Determining the Class of an Object
Want to find out what an object's class is? Here's the way to do it for an
object assigned to the variable key:
1. The getClass() method returns a Class object (where Class is itself a class)
that has a method called getName(). In turn, getName() returns a string
representing the name of the class.
For Example,
String name = key.getClass().getName();
2. The instanceOf operator. The instanceOf has two operands: a reference to an
object on the left and a class name on the right. The expression returns true or
false based on whether the object is an instance of the named class or any of that
class's subclasses.
For Example,
boolean ex1 = "Texas" instanceof String; // true
Object pt = new Point(10, 10);
boolean ex2 = pt instanceof String; // false