oop lecture5
TRANSCRIPT
Some concepts
Lecture 5
Object Oriented ProgrammingEastern University, Dhaka
Md. Raihan Kibria
Primitive types
public class PrimitiveDemo {
int i;//integer long l;//is longer than integer float fl;//float double dbl;//double; has more precision than float char[] charArray;//char array int[] intArray;//integer array boolean b;//true or false
public static void main(String[] args) { PrimitiveDemo demo = new PrimitiveDemo(); demo.charArray = new char[]{'E', 'A', 'S', 'T', 'E', 'R', 'N'}; for (int i=0; i<demo.charArray.length; i++) System.out.print(demo.charArray[i]); }}
Almost like the primitives in C:
Prints: EASTERN
Boxed typesA primitive like integer has a Boxed
equivalent:
Primitive Boxed
integer Integer
long Long
double Double
float Float
boolean Boolean
Integer I = null;//is possible because it is an objectBut int i = null;//is illegal because i is not an object
Type conversionpublic class TypeConversion {
public static void main(String[] args) { long longval = 234234234L; int intval = (int)longval; }}
Strings
Strings are objects in java. An object of String is created in the following:
public class StringDemo {
public static void main(String[] args) { String name1 = "john"; System.out.println(name1); }}
public class StringDemo { public static void main(String[] args) { String name1 = "john"; name1 = name1 + " kerry"; System.out.println(name1); }}
Strings can be concatenated:
Prints: john kerry
Methods
public class MethodDemo {
static void doSomething(){//static method System.out.println("hello"); }
void doALittle(){//instance method System.out.println("a text"); }
public static void main(String[] args) { //static method can be called without creating instance MethodDemo.doSomething();
//instance method must be called only on the instance MethodDemo demo = new MethodDemo(); demo.doALittle(); }}
Constructor
Constructor: as soon as an object is instantiated, constructor is called. Constructor is a method with the same name as the class. But there are no type modifiers (void, int, etc.) to the left of a constructor.
public class ConstructorDemo {
int i; public ConstructorDemo(){ i = 9; }
public void printValue(){ System.out.println("Value is: " + i); }
public static void main(String[] args) { new ConstructorDemo().printValue(); }}
Prints: value is: 9
public, protected, private modifiers
public definitions are accessible outside of package
protected definitions are accessible inside the package
private definitions are accessible only within the class
Example of public/privatepackage com;
public class A { public void doSomething(){ doSomethingPrivately(); }
private void doSomethingPrivately(){
}
public static void main(String[] args) {
}}
package net;
import com.A;
public class B {
public static void main(String[] args) { A a = new A(); a.doSomething(); }}
doSomethigPrivately() of A is not accessible from B