Welcome to Edukum.com

Class and Object

Class

class is a logical construct upon which the entire java language is built because it define the shape and nature of objects. As, such the class forms the basis for object oriented programming in java .Any concept you wish to implement in a java program must be encapsulated within a class.The most important thing to understand about a class is that it defines a new data type. Once defined, this new type can be used to create objects of that type. Thus class is a template for an object and object is an instance of class. A class is declared by use of the class keyword.Java class consists of two distinct types of information’s, attributes and behavior.

Attributes of class: Attribute are the data that differentiates one object from another .They can be use to determine the appearance ,state and other qualities of objects that belong to that class. In class, attributes are defined by variables.

Behavior of class: behavior refer to the things that a class of object can do themselves and other objects. behavior can be used to change the attributes of an object, receive information from other objects and send messages to other objects asking them to perform task. In class behavior are defined by method.

Creating class

Syntax

Class classname{

type instance-variable1;

type instance-variable2;

//..

type instance-variableN;

type methodName1(parameterList){

//body of method1

}

type methodName2(parameterList){

//body of method2

}

//….

type methodNameN(parameterList){

//body of methodN

}

}

The data or variables, defines within a class are called instance variable. The code is contained within a methods. Collectively ,the methods and variables defines within a class are called members of the class.

Example of class

public class Dog{

//Attributes

String breed;

int age;

String color;

//Behavior

void barking(){

}

 

void hungry(){

}

 

void sleeping(){

}

}

Creating Object

When you create a class, you are creating a new data type .You can use this type to declare objects of that type .However obtaining Object of a class is two step process .First, you must declare a variable of the class type .this variable doesn’t define an object .Instead, it is simply a variable that can refer to an object. Second, you must acquire an actual, physical copy of the object and assign it to the variable .You can do this using the new operator .The new operator dynamically allocates (i.e. ,allocates at run time )memory for an object and return a reference to it .this reference is, more or less ,the address in memory of the object allocated by new. This reference is then stored in the variable .thus in java, all class objects must be dynamically allocated.

As just explained ,the new operator dynamically allocates memory for an object .It has a general form:

Class-var =new classname();

Here ,class-var is a variable of the class type being created .The classname is the name of the class that is being instantiated . The classname followed by parentheses specifies the constructor for the class. A constructor defines what occurs when an object of a class is created .Constructors are an important part of all classes and have many significant attributes. Most real world classes explicitly defines their own constructors within their class definition. However ,if no explicit constructor is specified ,then java will automatically supply a default constructor.

 

Constructor

Java allows object to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor. A constructor initializes an object immediately upon creation .It has the same name as the class in which it resides and is syntactically similar to a method .Once defined ,the constructor is automatically called immediately after the object is created, before the new operator completes.

 

Example :

Class Box{

Double width ;

Double height;

Double depth;

//this is the constructor for Box

Box(){

System.out.println(“constructing box”);

width=10;

height=20;

depth=15;

}

//compute and return volume

Double volume () {

return width*height*depth;

}
}

class BoxTesting{

public static void main (String args[]){

//declare ,allocate ,and initialize Box objects

Box b1=new Box();

Box b2=new Box();

double vol;

//get the volume of first box.

vol=b1.volume ();

System.out.println(“Volume is “+vol);

//get the volume of second box.

vol=b2.volume ();

System.out.println(“Volume is “+vol);

}

}

When this program is run ,it generates the following results:

constructing box

constructing box

Volume is 3000.0

Volume is 3000.0

 

Overloading methods

If a class have multiple methods by same name but different parameters, it is known as Method Overloading.If we have to perform only one operation, having same name of the methods increases the readability of the program.Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. So, we perform method overloading to figure out the program quickly.

There are two way to overload the method in java

  1. By changing number of arguments .
  2. By changing the data type.

By changing number of arguments :

In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers.

Public class Calculation {

Void sum (int a,int b){

System.out.println(a+b);

}

Void sum (int a,int b,int c){

System.out.println(a+b+c);

}

Public static void main (String args[]){

Calculation obj=new Calculation();

obj.sum(10,20,30);

obj.sum(10,20)

}

}

 

Output of this program is:

60

30

By changing the data type:

In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two double arguments.

performs addition of three numbers.

Public class Calculation {

Void sum (int a,int b){

System.out.println(a+b);

}

Void sum (double a,double b){

System.out.println(a+b);

}

Public static void main (String args[]){

Calculation obj=new Calculation();

obj.sum(10.5,20.5);

obj.sum(10,20)

}

}

Output of this program is :

31.0

30

INTERFACE:

An interface is a kind of class that only contains the methods without any implementation. An interface is a named collection of method definitions (without implementations). An interface can also include constant declarations. Each variable that is defined in interface should be final and static. Interfaces are useful for the following:

  • Capturing similarities between unrelated classes without artificially forcing a class relationship
  • Declaring methods that one or more classes are expected to implement
  • Revealing an object's programming interface without revealing its class. (Objects such as these are called anonymous objects and can be useful when shipping a package of classes to other developers.)

Syntax

Interface SuperInterface {

//static and final variables

Public void function1();

Public int function2(int ,int);

}

Relationship between class and interfaces

As shown in figure below class extends another class ,interface extends another interface but class implements an interface .

Relationship_between_class_and_interfaces
Caption
fig: relationship between class and interface

Implementation of interfaces

A class never extends an interface rather it implements it. If any class implements any interface than that class should implement each and every function whose definition was in interface. Implementing an interface is like signing a contract with the compiler that states, “I will define all the methods specified by the interface”.

Class A implements SuperInterface {

@Override

public void function1(){

//function implementation.

}

@Override

public int function2(int a,int b){

//function implementation.

return a+b;

}

}

Leaving a method of an interface undefined in a class that implements the interface results in a compiler error.

Access modifier

AJava access modifierspecifies which classes can access a given class and its fields, constructors and methods. Access modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers are also sometimes referred to in daily speech asJava access specifiers, but the correct name is Java access modifiers. Classes, fields, constructors and methods can have one of four different Java access modifiers:

  • private
  • default (package)
  • protected
  • public

private Access modifier :

Method s, variables and constructors that are declared private can only be accessed within the declared class itself. Private access modifier is the most restrictive access level.Class and interface cannot be private. Variable that are declared private can be accessed outside the class if public getter methods are present in the class.Using the private modifier is the main way that an object encapsulates itself and hide data from the outside world.

Example:
public class Test{

private String name;

public String getName(){

return this.name;
}

public void setName(String name){

this.name=name;

}

}

Here ,the name variable of Test class is private ,so there’s no way for other classes to access directly.So to make this variable available to the outside world we define two public methods.

Default Access modifier:

Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc. A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public

Example:

boolean Test(){

return true;

}

Protected Access modifier:

Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class. The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected. Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.

Example

public class Test{

protected void msg(){

System.out.println(“hello”);

}

}

class Test1 extends Test{

public static void main(Srtring args[]){

Test1 obj= new Test1();

Obj.msg();

}

}

 

Public Access modifier:

A class, method, constructor, interface etc declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe. However if the public class we are trying to access is in a different package, then the public class still need to be imported. Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.

Example

public static void main (String[] args){

//……

}

The main method of an application has to be public .Otherwise ,it could not be called by java interpreter to run the class.

Arrays:

Anarrayis a collection of variables of the same type. For instance, an array ofintis a collection of variables of the typeint. The variables in the array are ordered and each have an index. Here is an illustration of Java arrays:


Array of 10 elements
Array of 10 elements

Array in java is index based, first element of the array is stored at 0 index.

Types of Array in java:

There are two types of array.

  • Single dimensional Array
  • Multidimensional Array.

Single dimensional Array:

Syntax to declare an Array in java

dataType[] arr;(or)

dataType []arr;(or)

dataType arr[];(or)

instantiation of an Array in java

arrayRefvar=new datatype[size];

example:

class Testarray{

public static void main(String args[]){

int a[]=new int[5];//declaration and instantiation

a[0]=10;//initialization

a[1]=20;

a[2]=70;

a[3]=40;

a[4]=50;

//printing array

for(int i=0;i<a.length;i++)//length is the property of array

System.out.println(a[i]);

}}

 

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization

multidimensional array in java :

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in java

dataType[][] arrayRefVar; (or)

dataType [][]arrayRefVar; (or)

80

 

 

dataType arrayRefVar[][]; (or)

dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java

int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in java

arr[0][0]=1;

arr[0][1]=2;

arr[0][2]=3;

arr[1][0]=4;

arr[1][1]=5;

arr[1][2]=6;

arr[2][0]=7;

arr[2][1]=8;

arr[2][2]=9;

Example of Multidimensional java array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

class Testarray3{

public static void main(String args[]){

//declaring and initializing 2D array

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array

for(int i=0;i<3;i++){

for(int j=0;j<3;j++){

System.out.print(arr[i][j]+" ");

}

System.out.println();

}

}}

Package
To make classes easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups of related classes into packages. A package is a collection of related classes and interfaces that provides access protection and namespace management. The classes and interfaces that are part of the JDK are members of various packages that bundle classes by function.

Some of the existing packages in Java are::

java.lang- bundles the fundamental classes
java.io- classes for input , output functions are bundled in this package

package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes.

Creating a package
While creating a package, you should choose a name for the package and include apackagestatement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.

Thepackagestatement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.

If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package.

Example:

Let us look at an example that creates a package calledanimals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes, interfaces.

Below given package example contains interface namedanimals:

package animals;

interface Animal{

public void eat();

public void travel();

}

If a class wants to use another class in the same package, the package name does not need to be used. Classes in the same package find each other without any special syntax.

To access the package from another package we must have to import that package in our program.

There are three ways to access the package from outside the package .

import package.*;
import package.classname;
fully qualified name.

using packagename.*
if you use package.* then all the classes and interface of this package will be accessible but not subpackages. The import keyword os used to make the classes and interfaces of another package accessible to the current package.

Using packagename.classname:

If you import packagename.classname then only declared class of this package will be accessible.

Using fully qualified name
if you use fully qualified name then only declared class of this package will be accessible .now there is no need to import .But you need to use fully qualified name every time when you are accessing the class or interface.It is generally used when two packages have same class name.for example java.util and java.sql packages contain Date class.

Inheritance
Inheritance is one of the most crucial concepts of object-oriented programming because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements. A class can have only one superclass, but each class can have an unlimited number ofsubclasses.

To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword.

Syntax of inheritance

class Subclass extends Superclass{

//member

}


© 2019 EDUKUM.COM ALL RIGHTS RESERVED


#Things To Remember



1063 Views