Download - Oop lecture3
Concepts of OOP
Lecture 3
Object Oriented ProgrammingEastern University, Dhaka
Md. Raihan Kibria
Difference between a Class and an Object
A class A class is a template Definition of a class is only given during design/coding
time A class can be compared to a struct in c
An object An object is an instance of a class An object is made only during run time An object is made from the definition of a class
An example
Class definition:
public class A{
String code; String name;
}
Code to make a new instance:A a = new A();
Object/instance
So far we have defined a class and written code to instantiate it. But we still have not created the object.
Compile: javac A.java Run: java A.class
Only now an object or instance of class A is created.
JVM creates the instance or object based on class definition found in the byte-code
Some rules for creating class in java
A class can be defined in any file. However, a public class must be in a file name that matches the class name.
Example of a public class:public class Student{ String code; String name;}file name: Student.java
Some rules for creating class in java
Example of non-public class:class A{ String name; String code;}
Class B{ int age; String program;}
Fliename could be anything, such as Example.java
Some rules for creating class in java
Please note that many non-public classes may reside in one file.
But a file can have only one public class. A file can have one public class and many
non-public classes.
Packages
Packages are folders, roughly speaking. Typically, “package” is the first line in any
java program. Many java files can be placed under a
package. Package is a way to organize codes.
Example
package com.abc;public class A{ String ...}
This means the file A.java is under folder com/abc
Example
public class B{ String ...}
This means the file B.java is not under any folder
Compiling packaged classes
Suppoer A.java is under com folder. The first line of A.java is: package com;
To compile issue commandjavac com/A.java The output A.class file will be produced
under com folder To run issue command: java com.A
Compiling non-packaged classes
Suppose B.java has no package definition To compile issue command:javac B.javaTo run issue command java B
Compiling a package
To compile all files under package issue command:
javac com/*.java
To compile multiple packages issue command:
javac com/*.java com/abc/*.java