Java: About Classes
Creating a Class | class Classname { .... } |
Creating Methods inside a Class | class Student { String lastname; String firstname; void printName() { System.out.println("Student's Name: " + firstname + " " + lastname); } } |
Create an Instance of a Class | Here is an example of the previously defined class:
Student s = new Student();Exercise |
Define a Subclass |
class GradStudent extends Student { .... }Exercise |
Class Protection Types | public package protection (default) More Details |
Components of a Class |
protected void finalize() throws Throwable { ...} class Car {
/*VARIABLES*/
String model;
String manufacturer;
float Engine_Size;
/*CONSTRUCTORS*/
Car(String m, String man) {
model = m;
manufacturer = man;
}
Car(String m, String man, float e) {
model = m;
manufacturer = man;
Engine_Size = e;
}
/*METHODS*/
void PrintInfo() {
System.out.println("Model:" + model);
System.out.println("Make: " + make);
System.out.println("EngineSize: " + Engine_Size);
}
}
|
Interface Class |
|
Abstract Class |
abstract void PrintInfo(); |
Package | Details |
Keywords |
|
Final |
|
Determining the Class of an Object
Below is an example of the instanceof operator that takes on the left the object and on the right the Class. It will return true if the object is an instance of this Class.if (S1 instanceof String) { System.out.println("It is a String!"); }
Another option is to "get the Name" of the object in questions class. This is done as follows:
String name = obj.getClass().getName();Exercise
Casting Objects
You are familiar with the idea of casting primitive types. You can do the same thing with objects as long as the class of the object your casting and the class you are casting to are related in terms of inheritance (one is the ancestor of the other or vica versa).Example:
(Journal) MyPaperhere we cast the object MyPaper that is an instance of the class Paper to the class Journal where Journal is a subclass of Paper.
Comparing Objects
You can compare if two objects refer to the same object in memory using the == and != signs.if(Object1 == Object2) { System.out.println("This is the same instance!"); }Exercise