Posted By:
1 Feb, 2014 8:34 am PST

Java overview and basic OOPS concepts

   Java Overview

Java is an:

· Object Oriented programming language originally developed by Sun Microsystems.

· It is platform independent which implies that unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.

 The way Java Works

 1.  Create a source code and save it as abc.java

2.  Compile the abc.java file by running the compiler application (javac). The compiler checks for errors and won’t let you compile until it’s satisfied that everything will run correctly.

3.  The compiler creates a new document, coded into javabytes (abc.class).  The compiler generated abc.class is made up of bytecodes. Any device capable of running java will be able to interpret/translate this file into something it can run. The compiled bytecode is platform independent. That is why java is guaranteed to be write once, run anywhere.

4.  Run the program by starting the Java Virtual machine(JVM) with the abc.class. The virtual machine reads and runs the bytecode. The JVM translates the bytecode into something the underlying platform understands, and runs the program.

 Conclusion: You’ll type a source code file, compile it using the javac compiler, and then run the compiled bytecode on a java virtual machine.

 As mentioned above, Java is an object oriented language because in Java everything is represented as an object; we’ll now examine what object orientation means.

 What is an object?

Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.

Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current speed) and behavior (changing gear, changing pedal, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.

Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?”  As you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming

Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages).

 What is a class?

A class is a blueprint or a prototype from which individual objects are created.

In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles

Consider dogs. Every dog has a breed, a color, and an age. The breed could be German shepherd, Cocker Spaniel, or some other breed. The color could be white, brown, etc. The age could be 2,5, etc. If we wanted to do some java programming with dogs, we would first need to create a file Dog.java. In this file, we would first define a class called Dog.

class Dog

{

}

The first line class Dog defines a class called Dog. Every class definition has to be followed by the curly braces { and }. All the programming related to the Dog class will be inside these curly braces.

Now we need to identify what information is required for each dog. As mentioned earlier, we need the breed, the color, and the age. We can therefore add there three variables inside the Dog class called breed, color, and age, as shown below:

Class Dog

{

breed;

color;

age;

}

Observe that each of the variables is followed by a semi-colon-each sentence in java has to end with a semi-colon. If you try to compile this file in java, you will get an error. You need to mention to java what data types the three variables will have. The first two are of type String whereas age is of type int. Make the change as shown below:

class Dog

{

String breed;

String color;

int age;

}

Save the file and compile it. You will see the class Dog.classhas got created. If you try and execute this class file, you will still get an error, since there is no main() method defined inside it.

  

  Add the main() method as shown below:

class Dog

{

String breed;

String color;

int age;

public static void main (String[] args)

     {

   }

} 

Save the file, compile it, and execute the class file. You will get this:

You have no code statements inside the main() method. Therefore, when you execute the class file, no action happens.

 ENCAPSULATION

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.

Encapsulation is the process of hiding the implementation details of a class and allowing access to the class through a public class.

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class.

In order to understand encapsulation, take the example of a TV remote control. It provides buttons for switching on the TV, switching off the TV, increasing/reducing the volume, changing the channel and so on. As a user of the remote control, we do not understand how the internal electronics of the remote control works-all we need to know is how to use the buttons.

You can think of the remote control as a java class which has multiple methods-one method is called switchOnTV(), the other switchOffTV(). We also have methods called increaseVolume(), reduceVolume(), and changeChannel(). We know that these methods are available to us at the click of a button – what happens inside once we click the button – we do not know, and nor do we care.

 Advantages of Encapsulation

1.Encapsulation makes it easy to maintain and modify code. For example, if we change the internal design of the class, the variable names, their data types, and so on, that change need not be known to the users of the class.  It gives us the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

2.Encapsulation, when used in the proper manner, makes it easy to define methods with standard names. For example, if an instance variable is called x, then the method to get the value of x is called getx(), and the method to set the value of x is called setx(). Such methods are known as getter and setter methods.

Example:

Let us look at an example that depicts encapsulation:

/* File name : EncapTest.java */

public class EncapTest{

    private String name;

   private String idNum;

   private int age;

    public int getAge(){

      return age;

   }

    public String getName(){

      return name;

   }

    public String getIdNum(){

      return idNum;

   }

    public void setAge(int newAge){

      age = newAge;

   }

    public void setName(String newName){

      name = newName;

   }

    public void setIdNum(String newId){

      idNum = newId;

   }

}

The public methods are the access points to this class' fields from the outside java world. Normally, these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters.

The variables of the EncapTest class can be access as below::

/* File name : RunEncap.java */

public class RunEncap{

    public static void main(String args[]){

      EncapTest encap =new EncapTest();

      encap.setName("James");

      encap.setAge(20);

      encap.setIdNum("12343ms");

       System.out.print("Name : "+ encap.getName()+

                             " Age : "+ encap.getAge());

    }

}

This would produce the following result:

Name:James Age:20

 Note: Mark instance variables as private and getters and setters as public for access control.

INHERITANCE

When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. With the use of inheritance the information is made manageable in a hierarchical order.

Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:

A hierarchy of bicycle classes.

 

 The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:

class MountainBike extends Bicycle {

     // new fields and methods defining

    // a mountain bike would go here

 }

This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.

When we talk about inheritance, the most commonly used keyword would be extends. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.

IS-A Relationship:

IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.

public class Animal{
}
 public class Mammal extends Animal{
}
 public class Reptile extends Animal{
}
public class Dog extends Mammal{
}

Now, based on the above example, In Object Oriented terms, the following are true:

· Animal is the superclass of Mammal class.

· Animal is the superclass of Reptile class.

· Mammal and Reptile are subclasses of Animal class.

· Dog is the subclass of both Mammal and Animal classes.

Now, if we consider the IS-A relationship, we can say:

· Mammal IS-A Animal

· Reptile IS-A Animal

· Dog IS-A Mammal

· Hence : Dog IS-A Animal as well

With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.

We can assure that Mammal is actually an Animal with the use of the instance operator.

In java, a class can have only one parent. Remember this: a class cannot extend more than one parent class. On the other hand, a parent class can have many child classes.

The class being extended is the parent class or the super class .

The class that extends a parent class is the child class or the sub class.

A class may be a child of one class and also a parent of one or more sub classes.


 Why use Inheritance?

· For Method Overriding (So Runtime Polymorphism).

· For Code Reusability.

 ABSTRACTION

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery. Abstraction lets you focus on what the object does instead of how it does it.

In OOPS, Abstraction refers to the ability to make a class abstract. An abstract class is one that cannot be instantiated. You just cannot create an instance of the abstract class. You can make a class abstract by adding the keyword abstract before the class declaration.

If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclass.

Example

abstract class canine extends Animal

{

public void roam() { }

}

POLYMORPHISM

Polymorphism is the ability of an object to take on many forms. Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object

Example:

Let us look at an example.

public interface Vegetarian{}

public   class Animal{}

public class Deer extends Animal implements Vegetarian{}

Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above example:

  • A Deer IS-A Animal
  • A Deer IS-A Vegetarian
  • A Deer IS-A Deer
  • A Deer IS-A Object

When we apply the reference variable facts to a Deer object reference, the following declarations are legal:

Deer d =new Deer();

Animal a = d;

Vegetarian v = d;

Object o = d;

All the reference variables d,a,v,o refer to the same Deer object in the heap.

 

Attachment: Inh.png


JAVA OVERVIEW AND OOPS CONCEPTS

Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).

With the advancement of Java and its widespread popularity, multiple configurations were built to suite various types of platforms. Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications.

Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.

 

TOOLS REQUIRED TO RUN A JAVA PROGRAM:

You will need a Pentium 200-MHz computer with a minimum of 64 MB of RAM (128 MB of RAM recommended).

You also will need the following softwares:

·         Linux 7.1 or Windows 95/98/2000/XP/7/8 operating system.

·         Java JDK 5 OR above

·         Microsoft Notepad or any other text editor or Eclipse IDE.

 

OBJECTS AND CLASSES:

In procedural languages such as C, we put all of our code in the main() method but Java is an object oriented language and so we have objects and classes which makes our task simpler.

 

Object: Any entity which has a state and behavior may be known as an object. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle. For example, in real life situations a car may have state such as color, name, model etc and behavior such as running, stationary etc. An object knows things and does things.Things an object knows about itself are called as instance variables and they represent the state of the object. The things that an object does are called as methods and they represent the behavior of the object.

Example: Alarm object have an instance variable to hold the AlarmTime and two methods for get_alarm() and set_alarm()for getting and setting the alarm time.

 

Class: A class is like a blueprint for an object.A class describes how to make an object of that class type. In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles.

 

Difference between class and object: A class is not an object but it is used to construct objects. Each object made from that class can have their own values for the instance variables of that class.

Let us start with creating our first Java object and class:

It has three types of variables:

Instance variables: These are those variables which are defined within a class but outside any method.

Local variables: They are defined inside the methods in a class.

Class variables: They are defined inside the class but outside the methods but they are defined with a keyword static.

An object declaration has the following syntax:

[class name] [object name] = new [class name]();

new keyword is used to create new objects of the class type.

A dotoperator(.) is used to access the variables and methods of the class whose object has been created.

 

Eg: c.display(); where c is the object name which is used to access the display method of the class car.

 

 

 

class cycle

{

String model;

int no;

void getcar(){

//Get the details of the car

}

}

Object creation :

cycle s=new cycle();

 

OOPS CONCEPTS

I. ENCAPSULATION:

 

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and overriding.

 

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

 

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

 

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

 

Example :To get the name and age of a person by encapsulating its data.

 

class EncapTest{

private String name;
private String idNum;
privateintage;

publicint getAge(){
returnage;
}

public String getName(){
returnname;
}

public String getIdNum(){
returnidNum;
}

publicvoid setAge( int newAge){
age = newAge;
}

publicvoid setName(String newName){
name = newName;
}

publicvoid setIdNum( String newId){
idNum = newId;
}
}

publicclass Encaps{
publicstaticvoid main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+
" Age : "+ encap.getAge());
}}

 

II. INHERITANCE:

 

Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.

 

When we talk about inheritance, the most commonly used keyword would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.

 

Syntax of extends:

public class superclass{

}

 

public class subclass extends superclass{

}

 

Example :To create a superclass and extend it to subclass

 

class Person

{

String FirstName;

String LastName;

 

Person(String fName, String lName)

{

FirstName = fName;

LastName = lName;

}

 

void Display()

{

System.out.println("First Name : " + FirstName);

System.out.println("Last Name : " + LastName);

}

}

 

class Student extends Person

{

intid;

 

Student(String fName, String lName, int nId)

{

super(fName,lName);

id = nId;

}

}

 

class Inheritance

{

publicstaticvoid main(String args[])

{

Person pObj = new Person("Rayan","Miller");

Student sObj = new Student("Jacob","Smith",1);

System.out.println("Person :");

pObj.Display();

System.out.println("");

System.out.println("Student :");

sObj.Display();

}

}

 

III.     POLYMORPHISM:

Polymorphism literally means taking more than one form .polymorphism is a characteristic of being able to assign a different behavior or value in a subclass,to something that was declared in a parent class.

Polymorphism means—One name many form.

In same class, if name of the method remains common but the number and type of parameters are different, then it is called method overloading in Java.
Overloaded methods:

1. appear in the same class or a subclass
2. have the same name but,
3. have different parameter lists, and,
4. can have different return types

 

Example :To overload one function with another

class overLoading {
publicstaticvoid main(String[] args){
polymorphism obj = new polymorphism();
obj.add(1,2);
obj.add("Life at "," MIT ");
obj.add(11.5, 22.5);
}
}
 
class polymorphism {
void add(int a, int b, int c){
int sum = a + b + c;
System.out.println("Sum of a+b+c is "+sum);
}
 
void add(double a, double b){
double sum = a + b;
System.out.println("Sum of a+b is "+sum);
}
 
void add(String s1, String s2){
String s = s1 + s2;
System.out.println(s);
}
}

 

IV.     OVERRIDING:

 

 If a class inherits a method from its super class, then there is a chance to override the method provided that it is not marked final.

The benefit of overriding is: ability to define a behavior that's specific to the subclass type which means a subclass can implement a parent class method based on its requirement.

Example :To override the display function of the superclass

 

class Person
{
String FirstName;
String LastName;
 
Person(String fName, String lName)
{
FirstName = fName;
LastName = lName;
}
 
void Display()
{
System.out.println("First Name : " + FirstName);
System.out.println("Last Name : " + LastName);
}
}
 
class Student extends Person
{
intid;
String standard;
String instructor;
 
Student(String fName, String lName, int nId, String stnd, String instr)
{
super(fName,lName);
id = nId;
standard = stnd;
instructor = instr;
}
void Display()
{
super.Display();
 
System.out.println("ID : " + id);
System.out.println("Standard : " + standard);
System.out.println("Instructor : " + instructor);
}
}
 
class Inheritance
{
publicstaticvoid main(String args[])
{
Person pObj = new Person("Rayan","Miller");
Student sObj = new Student("Jacob","Smith",1,"1 - B","Roma");
System.out.println("Person :");
pObj.Display();
System.out.println("");
System.out.println("Student :");
sObj.Display();
}
}

 

 V. ABSTRACTION

 

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

 

Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery. Abstraction lets you focus on what the object does instead of how it does it.

 

In OOPS, Abstraction refers to the ability to make a class abstract. An abstract class is one that cannot be instantiated. You just cannot create an instance of the abstract class. You can make a class abstract by adding the keyword abstract before the class declaration.

 

If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclass.

 

Example 

abstract class canine extends Animal

{

public void roam() { }

}

 

Was it useful?  




Please login to reply to this problem.