Session 2: Introduction to Object Oriented Programming Java Training Session 2: Introduction to Object Oriented Programming
Objectives Classes, Objects, Methods, Instance Variables Instantiating an Object of a Class Initializing Objects with Constructors Methods with Parameters Instance Variables, set Methods and get Methods Primitive Types vs. Reference Types Static Object Vs. Class
Objects Inspired by real life. Look around you, everything is object. Example: Marker in my hand. Computer Table Chair etc…
Object (Cont.) So, What is an object? Or what is the characteristics of an object? In simplest possible term – An object is a collection of Fields/Properties/(State) and Method/(Behavior). Let’s elaborate with example.
Illustration Meto Methods Methods Fields Methods Methods
A Pen Fields Method Height Radius Color Can open it’s cap Can write Can close it’s cap
Car Fields Methods Dimensions Speed Gear Direction Number of Wheels Number of Seats Number of Doors Methods Open door Start car Accelerate Break
Car Car Object!! openDoor start accelerate break changeDirection decelerate break changeDirection Car Type Wheels Doors Speed
Object in Action So far we have understood that object has some fields and some methods. To begin coding one more thing.. Constructor!! Each java object have some special method. (we will elaborate on this in future, after understanding inheritance) One of them is constructor. It’s method that is called when a object is created( more java term is “instantiated” ). Let’s see some codes now ..
Class: GradeBook, File: GradeBook.java Instance Variables – Note the naming convention public class GradeBook { private String courseName; private String courseTeacher; public GradeBook(String name) courseName = name; } public void setCourseName(String name) public String getCourseName() { return courseName; } public void displayMessage() System.out.println("CourseName is: " + courseName); public String getCourseTeacher() return courseTeacher; Constructor Public method - Carefully note the naming convention
Class: GradeBookTest, File: GradeBookTest.java public class GradeBookTest { public static void main(Stringargs[ ]) // Instantiate or create two GradeBook objects GradeBook gb1 = new GradeBook(“OOPL”); GradeBook gb2 = new GradeBook(“DS”); System.out.printf(“gb1 course name is: %s\n”, gb1.getCourseName()); gb1.setCourseName(“DLD”); System.out.printf(“gb1 course teacher is: %s\n”, gb1.getCourseTeacher()); // The above statement is trying to print something that is not initialized yet. }
Executing the Program To compile the source files type javacGradeBook.javaGradeBookTest.java Or, javac *.java It produces two class files named GradeBook.class and GradeBookTest.class To run the program type java GradeBookTest We used GradeBookTest as the argument to java as class GradeBookTest contains the “main” method. If we use “java GradeBook” then the JVM will throw an ERROR (more dangerous than an EXCEPTION) and will terminate immediately. Exception in thread “main” java.lang.NoSuchMethodError: main
Output of “java GradeBookTest” The String courseTeacher is “null”. But using a reference which is “null” will cause unexpected results or exceptions in many cases
Some Words on Multiple Classes in the Same Directory There is a special relationship between classes that are compiled in the same directory on disk. By default, such classes are considered to be in the same package – known as the default package. Classes in the same package are implicitly imported into the source code files of other classes in the same package. Thus, an import declaration is not required when one class in a package uses another in the same package.
Primitive Types vs. Reference Types Data types in Java are divided into two categories Primitive types boolean, byte, char, short, int, long, float and double By default, all primitive-type instance variables are initialized to 0 (except boolean which is initialized to “false”). Local primitive-type variables are not initialized by default. Reference types All nonprimitive types e.g. class variables By default, all reference-type instance variables are initialized to the special value “null”. “null” is a keyword in java. Local reference-type variables are not initialized by default. Java does not permit using a non-initialized variable before assigning a value to that variable. intn; // local variable of a method, not member of any class System.out.printf(“Value if n is: %d\n”, n); // compiler error (Example provided in LocalTest.java)
Object Vs Class Class is the definition Object is the instance Example It’s just the definition No real value is attach Object is the instance An object is the entity in ram that contains data. Example We all belongs to human class, but each of us is a different human object.
Basic flow of class and object Define Class Instantiate using “new” Create object Use the Object
Static!! Static fields and methods are unique to a class. One class has one single memory allocation for a static field. Static methods are accessed without instantiating the class. Ex: System.out.println(“Hello Java”); We will elaborate it later on. Example File: StaticTest.java and StaticMainTest.java
this Reference In a class there is always a reference present name this Which points to current object. Can’t use this in a static method as static methods are not related to a object.
Core Conception of OOP Encapsulation Polymorphism Inheritance
Encapsulation The most important thing software engineers want to achieve. It is a mechanism for restricting access to some of the object's components. Provide user methods to interact but user directly can not change the fields.
Encapsulation - Example Say we have a class name Student which has a field name mark and a method name calculateGrade() We will encapsulate the algorithm related to calculating grade depending on the method. Example: StudentTest.java
Let’s try some examples Write a class of Triangle. Fields Base Height Methods Constructor, Getter and Setters calculateArea
Let’s try some examples Now take use input of base and height Then create object depending on the user input.
Let’s try points Now write a class of Point Fields Methods X Y Constructor, Getter and Setters Print() // just print the coordinates distance(Point) //calculate the distance between this point the provided point
Back to triangle Add a method name compare(Triangle) That will compare the area of this triangle and the provided triangle.
Few things JRE – the package containing only JVM and related software. Can’t compile java codes with a jre. JDK – the package containing software to run and compile java code. Java Doc – All class function’s detail is provided in java doc format. http://download.oracle.com/javase/6/docs/api/ Java Tutorial – Official java tutorial from oracle.