Saturday, August 16, 2014

Java Classes and Methods

Class

Classes are user defined data type and behave like built-in types. A class is blue print for group of objects that have the same properties and common behaviour.A class can have many object

class <classname> extends <superclassname>
  { <variable declaration;>
          <method declaration;>
   }

Object
Object in java are created using new operator.It is an instantiation of a class. Three characteristics of object
  • The object's behavior - what method can apply to it.
  • The object's state -how does the object react when method apply those method.
  • The object's identity-how is the object distinguish from other that may have the same behavior and state.
Syntax for creating object: class-name var=new class-name(); Ex :Let Fruit is a class and Mango is object. Fruit mango; //declare mango =new Fruit();//instantiate Methods :
  • Constructors :It enable the object to initialize itself when it is created.Constructor has same name as class itself.They do not have return type,not even void. B'coz they return the instance of the class itself.
example:
public class Student {
    public String firstName; // First name
    public String lastName;  // Last name
    public int    id;        // Student id

    public Student(String fn, String ln, int idnum)
     {
        firstName = fn;
        lastName  = ln;
        id        = idnum;
    }
}

public class TestStudent {
    public static void main(String[] args) {
        Student t1;

        //... Create new Student object with new.
        t1= new Student("Tatiana", "Johnson", 9950842);
}
}

  • Method Overloading:Methods that have same name, but different parameter lists and different definition.It is used when object has to perform similar task but using different input parameter.
  • Overriding Methods:A method define in the subclass,has same name,same argument and same return type as a method in the superclass.Then , when that method is called,the method defined in the subclass is invoked and excuted instead of the one in the superclass.
Interface

Although a java class can't be a subclass of more than one superclass,it can implement more than one interface.An interface is a kind of class.Like classes,interfaces contain method and variables but with a major difference .The difference is that interface define only abstact method and final fields. This means that interface do not specify any code to implement these method and data field contain only constant.It is the resposibility of the class that implement an interface to define the code for implementation of these method.
Syntax:
interface Interfacename {
        <variable declaration>;// varialbe will be constant.
        <method declaration>;//method will not contain anybody.
}

Like classes, interface can also be extended .The new subinterface will inherit all the members of the superinterface in the manner similar to subclasses. Syntax:
interface name2 extends name1 {
    body of name2
}
Example:
class Student {
   int rollNumber;
   void getNumber(int n) {
          rollNumber=n;
  }
  void putNumber() {
        System.out.println("Roll No:" +rollNumber);
  }
}

class Test extends Student {
   float Hindi,Maths;
   void getMarks(float m1,float m2) {
         Hindi=m1; Maths=m2;
   }
  void putMarks() {
    System.out.println("Marks obtained");
    System.out.println("Hindi marks="+Hindi);
    System.out.println("Maths marks="+Maths);
   }
} 

interface
interface sports {
   public static final float sportWt=6.0F;
  
    void putWt();
}

class Result extends Test implements sports {
    float total;
   public void putWt() {
     System.out.println("sports wt.=" +sportWt);
   }
   void display() {
     total=Hindi+Maths+sportWt;
     putNumber();
     putMarks();
     putWt();
     System.out.println("Total score=" +total);
   }
}

class Marksinput {
    public static void main ( String args ) {
          Result student1=new Result();
          student1.getNumber(1234);
          student1.getMarks(27.5F,33.0F); student1.display();
     }
}

Abstraction 

Abstract classes are used to declare common characteristics of subclasses.abstract class cannot be instantiated.Only its subclasses can be instantiated abstract method does not contain any body.
public abstract class LivingThing {
      public void breath(){
        System.out.println("Living Thing breathing...");
      }
      public abstract void walk();//can't define here
}

public class Human extends LivingThing{
      public void walk(){ System.out.println("Human walks...");
  }
}

class AbstractDemo{
       public static void main(String args[]) {
           Human b = new Human(); b.walk(); b.breath();
       }
}

Packages
It means grouping a variety of classes or interfaces together.Packages are container for classes. Many programming language support the concept of libraries.In C they are known as header files,In C++ they are termed as class libraries ,whereas in Java they are termed as packages.
Syntax:
package <package name>;
Syntax for import statement:
import <package-name>.*;
import <package-name>.<class-name>;
Note:' * ' implies that all classes of that particular package are imported in the program.
Benefit of package:
  • The classes contained in the packages of other program can be easily reused.
  • In packages, classes can be unique compared with classes in other package.That is, two classes in two different packages can have the same name.They may be reffered by their fully qualified name,comprising the package name and the class name.
  • Package provides a way to hide classes thus preventing other program or package from accessing classesthat are meant fo internal use only.
  • Packages also provides a way for separating "deign" from "coding".First we can design classes and decide their relationship,and then we can implement the java code needed for the methods.It is possible to change the implementation of any method without affecting the rest of th design.
Types of packages:
  • Java system packages
  • User defined packages
Packages and Access control
Acess control can be defined as the method by which interaction with resources are restricted to collection of user or program for the purpose of security, privacy or availability constraint.
LocationPrivatedefaultProtectedPublic
same classyesyesyesyes
same package and also a subclassnoyesyesyes
same package but not subclassnoyesyesyes
different package but subclassnonoyesyes
different package but not a subclassnononoyes
Consider an existing package that contains a class called “Teacher”: This class is stored in “Teacher.java” file within a directory called “pack1”. How do we a new public class called “Student” to this package.
package pack1;

public class Teacher{

   public void displayTeacher(){
     System.out.println("I'm a Teacher");
   }
}

package pack1;

public class Student{

   public void displayStudent(){
     System.out.println("I'm a student");
   }
}

package pack2;

public class Teacher{
  
   public void displayTeacher(){
     System.out.println("I'm a Teacher");
  }
}


package pack2;

public class Student{  

  public void displayStudent(){
    System.out.println("I'm a student");
  }
}

Handling Name Clashing
In Java, name classing is resolved by accessing classes with the same name in multiple packages by their fully qualified name.
Example:
import pack1.*;

import pack2.*;

pack1.Student displayStudent;

pack2.Student displayStudent;

Extending a Class from Package
A new class called “Professor” can be created by extending the “Teacher” class defined the package “pack1” as follows:
import pack1.Teacher;

public class Professor extends Teacher{

  public static void main(String args[]){
     Teacher t1= new  Teacher ();
     t1.displayTeacher();
  }

  // body of Professor class
  // It is able to inherit public and protected members,
  // but not private or default members of Teacher class.
}
output:  I'm a teacher.
package  school;

public class Person {

    private String name;
    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}


package school;
public class Student extends Person {

    private String schoolName;
    private double grade;

    public String getSchool() {
        return schoolName;
    }

    public void setSchool(String school) {
        this.schoolName = schooNamel;
    }

    public double getGrade() {
        return grade;
    }

    public void setGrade(double grade) {
        this.grade = grade;
    }
}


package school;
public class CollegeStudent extends Student {

    /** Creates a new instance of CollegeStudent */
    public CollegeStudent() {
    }

    private String college;
    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }

}
Write Teacher.java. Note that Teacher class is a sub-class of Person class.
package school;public class Teacher extends Person {
private String subject;  
public String getSubject() {  
return subject;  
}
public void setSubject(String subject) {  
this.subject = subject;  
}}
public class Main { public static void main(String[] args) { Person person1 = new Person(); person1.setName("Anil kapoor"); Student student1 = new Student(); student1.setName("Priya dutta"); student1.setSchool("Delhi public school "); CollegelStudent collegeStudent1 = new CollegeStudent(); collegeStudent1.setName("Bill Clinton"); collegeStudent1.setSchool("Delhi public school "); collegeStudent1.setCollege("JNU Delhi"); Teacher teacher1 = new Teacher(); teacher1.setName("Dipika Pandey "); teacher1.setSubject("Maths"); // Display name of object instances using the getName() method // defined in the Person class. System.out.println("Displaying names of all object instances..."); System.out.println(" person1.getName() = " + person1.getName()); System.out.println(" student1.getName() = " + student1.getName()); System.out.println(" CollegeStudent1.getName() = " + collegeStudent1.getName()); System.out.println(" teacher1.getName() = " + teacher1.getName()); } }
OUTPUT
Displaying names of all object instances...
person1.getName() =Anil kapoor
student1.getName() =Priya dutta
collegeStudent1.getName() = Bill Clinton
teacher1.getName() = Dipika Pandey
More on Java

No comments:

Post a Comment