Sie sind auf Seite 1von 39

Java Fundamentals

•Features of Object oriented programming


•History of Java
•Features of Java
•Java Virtual Machine Architecture
•Difference between C++ and Java
•Reflection byte codes
Features of Object- Oriented Programming
• Class:
– A blueprint or prototype from which objects are created.
– A class contains variables (data types) and methods (functions) to
describe the behavior of an object.
– Example: class Computer
class Class_Name {
String Maker;
{ int Model;
member variables String Color;
methods void turnOn
{
} //statement(s)
}
void turnoff
{
//statement(s)
}
}
Features of Object- Oriented Programming
• State: Maker, Model, Color etc.,
Behavior: Turn on, Turn off etc.,
• Object:
– Object is a software bundle of related state and behavior.
– Object is an instance of a class.
– Example:
• To create an object:
Computer laptop = new Computer();

Class: Computer
Object: laptop
Keyword: new
Constructor: Computer()
Features of Object- Oriented Programming
• Inheritance:
– A process where one class inherits the properties of another class.
– In inheritance, two keywords exist:
• extends and
• implements
– extends:
• Allow the child class to inherit all the properties (data members and
methods) of the parent class
• In addition to these, new data members and methods can be created.
• Example:
Features of Object- Oriented Programming
Features of Object- Oriented Programming
• Implements
– Inherits the properties from an interface. Interfaces cannot be extended by
the classes.
– Example:
Features of Object- Oriented Programming
• Implements
interface mammal
{
public void walk();
}
public class lions implements mammal
{
public void walk()
{
System.out.println(“Lions walk on 4 legs");
}
public class humans implements mammal
{
public void walk()
{
System.out.println(“humans walk on 2 legs");
}

}
Features of Object- Oriented Programming
• Implements
public class whales implements mammal
{
public void walk()
{
System.out.println(“Whales have no legs");
}

public static void main(String args[])


{
mammal m= new whales();
m.walk();
}
}
Features of Object- Oriented Programming
• Encapsulation:
– A mechanism of binding code and data together in a single unit.
– Encapsulation is also known as “data Hiding“.
– Example :
» Capsule. Different powdered or liquid medicines are encapsulated inside a capsule.
Features of Object- Oriented Programming
public class EncapsTest
class Employee
{
{ public static void main(String
private String empName; args[])
{
public String getEmpName() Employee emp1 = new
Employee();
{
empl.setEmpName("Mario");
return empName;
} System.out.println
public void ("Employee Name: " +
setEmpName(String newValue) empl.getEmpName());
{ }
}
empName = newValue;
}
}
Features of Object- Oriented Programming
• Advantages of encapsulation:
– Improves maintainability and flexibility and re-usability:
– The fields can be made read-only (If we don’t define setter methods
in the class) or write-only (If we don’t define the getter methods in
the class).
– User would not be knowing what is going on behind the scene.
Features of Object- Oriented Programming
• Polymorphism:
– Allows us to perform a task in multiple ways.
– ‘Poly’ means ‘Many’ and ‘Morphos’ means ‘Shapes’.
Features of Object- Oriented Programming
• Polymorphism:
– Two types of polymorphism exist:
» Method Overloading: (Static Polymorphism/Compile time
polymorphism)
» Method Overriding: (Dynamic Polymorphism/Run time
polymorphism)
Features of Object- Oriented Programming
• Method Oveloading: (Dynamic Polymorphism/Run time polymorphism)
• Example: Consider two students in a class. One student has the same first
names and last name. Other student has the same first name, different
middle name and last name.
• Example: Ram Joshi and Ram Anant Joshi. The teacher takes the
attendance(Compiler). Now the signatures are different . Student may
sign as “Ram Joshi” and other student with the same first name may
sign as “Ram Anant Joshi”.
• Implementation:
Features of Object- Oriented Programming
class DemoOverload
{
public String studentname(String fname, String lname)
{
String n = fname+lname;
return n;
}
public String studentname(String fname, String mname, String lname)
{
String n = fname+ mname +lname;
return n;
}
}
class Test
{
public static void main(String[] args)
{
DemoOverload demo=new DemoOverload();
System.out.println(demo.studentname("Ram","Joshi")); //method 1 called
System.out.println(demo.studentname("Ram","Anant","Joshi")); //method 2 called
}
Features of Object- Oriented Programming
• Conclusion:
– The first method “studentname “ takes two parameters while the
second one takes three. The compiler (in this case the teacher) looks
at the method signature and determines who is the student.
Features of Object- Oriented Programming
• Method Overriding: (Dynamic Polymorphism/Run time polymorphism)
• Example: Consider two students in a class. Two students have the same
first name, middle name and last name.Now, their signatures as almost
the same. Now, how will the teacher(in this case the compiler) identify the
students’ signature with exactly the same names
• Example: 2 students “Ram Anant Joshi” and “Ram Anant Joshi”. The
teacher takes the attendance(Compiler). Now the signatures are exactly
the same. Both students may sign as “Ram Anant Joshi”. Now how will
the teacher differentiate the 2 students?
• Implementation:
Features of Object- Oriented Programming
public interface parentreference
{
public String studentname(String fname, String mname, String lname);
}
public class ramanantjoshi1 implements parentreference
{
public String studentname(String fname, String mname, String lname)
{
String n = fname+ mname +lname;
return n;
}
}
public class ramanantjoshi2 implements parentreference
{
public String studentname(String fname, String mname, String lname)
{
String n = fname+ mname +lname;
return n;
}
}
Features of Object- Oriented Programming
public class Test
{
public static void main(String[] args)
{
parentreference pref = new ramanantjoshi1();
System.out.println(pref. studentname(“Ram”, “Anant”, “Joshi”));

parentreference pref = new ramanantjoshi2();


System.out.printlnpref. studentname(“Ram”, “Anant”, “Joshi”));
}
}
Features of Object- Oriented Programming
• Conclusion:
– The first method “studentname “ takes two parameters while the
second one takes three. The compiler (in this case the teacher) looks
at the method signature and determines who is the student.
Features of Object- Oriented Programming
• Abstraction:
– A process of hiding the implementation details from the user, only the
functionality will be provided to the user.
– In other words, the user will have the information on what the object does
instead of how it does it.
– In Java, abstraction is achieved using Abstract classes and interfaces.
– Example
History of object oriented programming
• SIMULA 1(1962) and SIMULA 2(1967) are the 2 earliest OO languages.
• The above languages were developed at Norwegian Computing Center,
Norway.
• Most OOP concept found in SIMULA languages.
• OOP began to flourish with C++.
• C was the parent language of C++.
• C++ was developed by Bjarne Stroustrup.
• OOP was used in the language called Oak to develop intelligent electronic
devices capable of being centrally controlled from a handheld device(eg:
remote control) . The Oak programming was finally given the name Java
because the it was discovered that a language by that name already
existed.
• Java gained popularity because of the internet.
• C# is Microsoft’s answer to JAVA
History of Java
• Java was developed by James Gosling , Patrick Naughton, Ed Frank ,Chris
Warth and Mike Sheridan at sun microsystems , in 1991.
• Initially designed for the development of software for consumer electronic
devices like TVs, VCRs, toasters, microwave ovens and other electronic
machines.
• With emergence of the internet, java gained its popularity.
• A general purpose object-oriented programming language(A technique
to think real world in terms of objects).
• Note:
– Java is not an enhanced version of C++.
• Goal to develop java:
– To make the language simple, portable and highly reliable.
Features of Java
• Compiled and interpreted:
– Two-stage system:
• Java is both compiler and interpreted language.
• Java compiler translates source code into bytecode
• Java interpreter interprets bytecode to the machine code.
• diagrammatic representation of how java compiles and interprets(To be
included)
• Platform Neutral and portable:
– Java is not tied to any hardware or OS. Thus java programs can be moved from one
computer system to another.
– Therefore java is a popular language of the internet.
• Object-oriented:
– Everything in java is an object.
– All the code and data reside within classes. Objects are instances of classes.
– Eg:
• Robust and secure:
– Strict compile time and run time checking for data types.
– Automatic garbage collection thereby handling memory management
problems.
– Exception handling:
• Captures errors and eliminates any risk of crashing the system.
– Security:
• Since java is used for internet, it ensures that no viruses are
communicated with an applet.
• Absence of pointers ensures that programs cannot gain access to
memory locations with proper authorizations.
• Distributed:
– Java can access remote objects on a network as easily as they can in a
local system.
– Programmers sitting at multiple remote locations can collaborate and
work together on a single project.
• Multithreaded and interactive:
– Multiple tasks handled simultaneously.
– Eg: listening to an audio clip while taking the printout of the document
,downloading an applet,watching video clips simultaneously.
• High performance:
– Performance is better due to intermediate bytecode.
– Multithreading further enhances the overall execution speed of java
programs.
• Dynamic and Extensible:
– Linking new class libraries, methods and objects.
– Support functions written in other languages such as C and C++. These
functions are known as native methods.
• Java is a strongly typed language:
– A strongly typed language checks the type of a variable before
performing an operation on it, whereas a weakly typed language does
not.
– Example:
Java Code:
int i = 10;
boolean b = true;
System.out.println(i + b); //compile error. Can't add int with boolean
System.out.println(i + (int) b); //compile error. Can't cast boolean to int

C, on the other hand, is a weakly typed language.


int i = 10;
bool b = true;
printf("%d", i + b); //Prints 11
Two paradigms that govern how a program is constructed
• process-oriented programs:
– Programs consists of series of steps(i.e. code).
– Eg: procedural languages such as “C” employ this model.
– Disadvantages:
• Complexity increases as the program grows larger.
• Object-oriented programs:
– Revolving round objects.
– Advantages:
• Manages code complexities to a large extent
Two ways of using java

• Java can be used to create two types of


programs:
– Applications:
• Programs that run on your computer under the OS of that
computer
– Applets:
• Programs designed to be transmitted over the internet
and executed by java-compatible web browser.
• diagram
Java Virtual Machine(JVM)

• Java Virtual Machine, or JVM


– “virtual” computer that resides
in the “real” computer as a
software process.
– In other words, JVM is It is a machine
implemented in software. language for
– Gives Java the flexibility of JVM
platform independence.
– It is a program that interprets the
intermediate bytecode and
generates desired output.
– Diagrammatic representation:

Does not have to worry about


Hardware/OS. Thus portability
is offered.
Components of JVM

• Stack:
– stores various method arguments as well as the local variables of any
method.
• Heap:
– Here the objects are stored.
– Whenever we allocate an object using new operator, the heap comes
into picture and memory is allocated from there.
– Unlike C++, Java does not have free operator to free any previously
allocated memory. Java does this automatically using Garbage
collection mechanism
• Method Area
– Area where bytecodes reside.
– The program counter points to some byte in the method area.
– Eg of java code
public static void main(String[] args)
{
// 3 local variables
Box b1 = new Box();
Box b2 = new Box();
Box b3 = new Box();
}
Stack Heap

b3 Box Object

b2 Box Object

b1
Box Object
• How Java Works?
• What is run in java to run a java application?
• Code structure in java
Interpretation of java class and public static void main()

• Class declaration:
– All the code must be placed inside a class.
– Eg
• Opening brace and closing brace:
– Every class in java begins with “{“ and ends with “}”
• public static void main(String args[]):
– main():
• It is the name of the method inside the class.
• Every java application must have one main().
• Indicates the starting point for the interpreter to begin the execution of the program.
• A java application can have any number of classes but only one class must have
main() to initiate the execution.
– Access specifiers in main()
• public:
– main() must be declared as public since it must be called
outside the class when the program is executed.
• static:
– Indicates that main() belongs to the entire class and not a part
of any objects of the class.
– main() must always be declared as static since the interpreter
uses this method before any objects are created.
• void:
– Indicates main() does not have any return value.
• Diagrammatic representation:
• egs