• Save
Introduction to class in java
Upcoming SlideShare
Loading in...5
×
 

Introduction to class in java

on

  • 6,287 views

fundamental of class object and methods in core java, core java easy guide ppt of chapter 5 of http://www.java2all.com/

fundamental of class object and methods in core java, core java easy guide ppt of chapter 5 of http://www.java2all.com/

Statistics

Views

Total Views
6,287
Views on SlideShare
5,878
Embed Views
409

Actions

Likes
5
Downloads
0
Comments
0

2 Embeds 409

http://www.java2all.com 351
http://java2all.com 58

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters

Introduction to class in java Introduction to class in java Presentation Transcript

  • Chapter 5Introduction To Class http://www.java2all.com
  • What is class?• Class is a collection of data members and member functions.Now what are data members?• Data members are nothing but simply variables that we declare inside the class so it called data member of that particular class. http://www.java2all.com
  • Now what are member functions? Member functions are the function or you can say methods which we declare inside the class so it called member function of that particular 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, a class is a template for an object, and an object is an instance of a class. Because an object is an instance of a class, you will often see the two words object and instance used interchangeably. http://www.java2all.com
  • Syntax of class:class classname{ type instance-variable; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method }} http://www.java2all.com
  • • When you define a class, you declare its exact form and nature. You do this by specifying the data that it contains and the code that operates on that data.• The data, or variables, defined within a class are called instance variables. The code is contained within methods.• NOTE : C++ programmers will notice that the class declaration and the implementation of the methods are stored in the same place and not defined separately. http://www.java2all.com
  • Example :public class MyPoint{ int x = 0; int y = 0; void displayPoint() { System.out.println("Printing the coordinates"); System.out.println(x + " " + y); } public static void main(String args[]) { MyPoint obj; // declaration obj = new MyPoint(); // allocation of memory to an object obj.x=10; //access data member using object. obj.y=20; obj.displayPoint(); // calling a member method }} http://www.java2all.com
  • Syntax:accessing data member of the class: objectname.datamember name;accessing methods of the class: objectname.methodname();So for accessing data of the class:we have to use (.) dot operator.NOTE: we can use or access data of any particular class without using (.) dot operator from inside that particular class only. http://www.java2all.com
  • Creating Our FirstClass Object http://www.java2all.com
  • Creating Our First Class Object The program we gave in previous topic from thatwe can easily learn that how object is going to declare anddefine for any class. http://www.java2all.com
  • Syntax of object:classname objectname; declaration of object.objectname = new classname(); allocate memory to object (define object).or we can directly define object like thisclassname objectname = new classname(); http://www.java2all.com
  • import java.text.DecimalFormat;public class Time1 extends Object{ private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public Time1() We would use this class to { setTime( 0, 0, 0 ); display the time, and control } how the user changed it. public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } http://www.java2all.com
  • import java.text.DecimalFormat;public class Time1 extends Object{ private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public Time1() { setTime( 0, 0, 0 ); } public void setTime( int h, int m, int s ) { We can only have one public class per file. hour = ( class >= 0 && be < 24 ) in h : 0 called This ( h would h stored ? a file ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); “Time1.java.” second = ( ( s >= 0 && s < 60 ) ? s : 0 ); Question: Does that mean we can include other classes } in our file—if they are not declared public? http://www.java2all.com
  • import java.text.DecimalFormat;public class Time1 extends Object{ private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public Time1() { setTime( 0, 0, 0 ); } In keeping with encapsulation, the member- access modifiers declare our instance variables public void setTime( int h, int m, int s ) { private. hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); When this ( ( m >= 0 && m < 60 ) ? m the only way minute = class gets instantiated, : 0 ); to access = ( ( svariables is through :the); second these >= 0 && s < 60 ) ? s 0 methods } of the class. http://www.java2all.com
  • import java.text.DecimalFormat;public class Time1 extends Object{ The Constructor private int hour; // 0 - 23 method “ Time1()” private int minute; // 0 - 59 private int second; // 0 - 59 must have the same name as the class so public Time1() { the compiler always setTime( 0, 0, 0 ); knows how to } initialize the class. public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } http://www.java2all.com
  • import java.text.DecimalFormat;inThe method setTime()takes the time arguments. Itvalidates the Time1 extends Objectseconds to make sure theypublic class hours, minutes andmake sense. Now you can see why the concept of a class{ private int hour; // 0 - 23might be prettyminute; // 0 - 59 private int nifty. private int second; // 0 - 59 public Time1() { setTime( 0, 0, 0 ); } public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } http://www.java2all.com
  • Using Our New Class• We cannot instantiate it in this class.• We need to create another class to do actually make anexample of this class. http://www.java2all.com
  • Using Our New Class• We need to create a driver program TimeTest.java• The only purpose of this new class is to instantiate andtest our new class Time1. http://www.java2all.com
  • Introduction To Method http://www.java2all.com
  • • As we all know that, classes usually consist of two things instance variables and methods.• Here we are going to explain some fundamentals about methods.• So we can begin to add methods to our classes.• Methods are defined as follows• § Return type• § Name of the method• § A list of parameters• § Body of the method. http://www.java2all.com
  • Syntax:return type method name (list of parameters){ Body of the method}• return type specifies the type of data returned by the method. This can be any valid data type including class types that you create.• If the method does not return a value, its return type must be void, Means you can say that void means no return. http://www.java2all.com
  • • Methods that have a return type other than void return a value to the calling routine using the following form of the return statement:• return value; Here, value is the value returned.• The method name is any legal identifier.• The list of parameter is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called.• If the method has no parameters, then the parameter list will be empty. http://www.java2all.com
  • import java.util.Scanner;class Box{ double width; double height; double depth; void volume() // display volume of a box { System.out.print("Volume is : "); System.out.println(width * height * depth); }}class BoxDemo{ public static void main(String args[]) { Box box1 = new Box(); // defining object box1 of class Box Scanner s = new Scanner(System.in); System.out.print(“Enter Box Width : ”); box1.width = s.nextDouble(); System.out.print(“Enter Box Height : ”); box1.height = s.nextDouble(); System.out.print(“Enter Box Depth : ”); box1.depth = s.nextDouble(); // display volume of box1 box1.volume(); // calling the method volume }} http://www.java2all.com
  • Constructors http://www.java2all.com
  • Constructors• The Constructor is named exactly the same asthe class.• The Constructor is called when the newkeyword is used.• The Constructor cannot have any return type —not even void. http://www.java2all.com
  • Constructors• The Constructor instantiates the object.• It initializes instance variables to acceptable values.• The “default” Constructor accepts no arguments.• The Constructor method is usually overloaded. http://www.java2all.com
  • Varieties of Methods: Constructors• The overloaded Constructor usually takes arguments.• That allows the class to be instantiated in a variety ofways.• If the designer neglects to include a constructor, then thecompiler creates a default constructor that takes noarguments.• A default constructor will call the Constructor for theclass this one extends. http://www.java2all.com
  • public Time2(){ setTime( 0, 0, 0 );} • This is the first Constructor. • Notice that it takes no arguments, but it still sets the instance variables for hour, minute and second to consistent initial values of zero. http://www.java2all.com
  • public Time2(){ setTime( 0, 0, 0 );}public Time2( int h, int m, int s ){ setTime( h, m, s );}• These are the first two Constructors.• The second one overrides the first.• The second Constructor takes arguments.• It still calls the setTime() method so it can validatethe data. http://www.java2all.com
  • public Time2(){ setTime( 0, 0, 0 );} Usually, we can’t directly access the private instance variables of anpublic Time2( int h, int m, int s ){ object, because it violates setTime( h, m, encapsulation. s );} However, objects of the same class arepublic Time2( Time2 time access each other’s permitted to ){ instance variables directly. setTime( time.hour, time.minute, time.second );} • This final constructor is quite interesting. • It takes as an argument a Time2 object. • This will make the two Time2 objects equal. http://www.java2all.com
  • public class Employee extends Object{ private String firstName; private String lastName; private static int count; // # of objects in memory public Employee( String fName, String lName ) { firstName = fName; lastName = lName; ++count; // increment static count of employees System.out.println( "Employee object constructor: " + firstName + " " + lastName ); } protected void finalize() Because count is declared as private static, the { —count; // decrement static count of employees System.out.println( "Employee object finalizer: " + firstName + " " + to access + only way lastName its data "; count = "by count ); public is + using a } static method. public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public static int getCount() { return count; }} http://www.java2all.com
  • public class Employee extends Object{ private String firstName; private String lastName; private static int count; // # of objects in memory public Employee( String fName, String lName ) { firstName = fName; lastName = lName; ++count; // increment static count of employees System.out.println( "Employee object constructor: " + firstName + " " + lastName ); } protected void finalize() { —count; // decrement static count of employees System.out.println( "Employee object finalizer: " + firstName + " " + lastName + "; count = " + count ); } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public static int getCount() { return count; }} http://www.java2all.com
  • AccessModifiers http://www.java2all.com
  • Superclasses and Subclasses Impact on Access Modifiers • Access Modifiers are among the thorniest and most confusing aspects of OOP. • But, remember, encapsulation is one of the primary benefits of object orientation, so access is important. http://www.java2all.com
  • Superclasses and Subclasses Impact on Access Modifiers • The familiar private access modifier lets us shield our instance variables from the prying eyes of the outside world. • Relying on Access Modifiers, you can shield both your class’s private instance variables and its private methods. http://www.java2all.com
  • Superclasses and Subclasses Impact on Access Modifiers • With those ends in mind, Java lets review the four different levels of access: private, protected, public and the default if you don’t specify package. http://www.java2all.com
  • Superclasses and Subclasses • A summary of the various types of access modifier: Specifier class subclass package world private X package X X protected X X X public X X X X http://www.java2all.com
  • Superclasses and Subclasses • As you can see, a class always has access to its own instance variables, with any access modifier. Specifier class subclass package world private X package X X protected X X X public X X X X http://www.java2all.com
  • Superclasses and Subclasses• The second column shows that Subclasses of thisclass (no matter what package they are in) have accessto public (obviously) and protected variables. Specifier class subclass package world private X package X X protected X X X public X X X X http://www.java2all.com
  • • Therefore, the important point?Subclasses can reach protected-access variables,but can’t reach package-access variables…unless the Subclasses happen to be saved in thesame package. http://www.java2all.com
  • Superclasses and Subclasses• The third column “package” shows that classes inthe same package as the class (regardless of theirparentage) have access to data variables. Specifier class subclass package world private X package X X protected X X X public X X X X http://www.java2all.com
  • Superclasses and Subclasses • In the fourth column, we see that anything and anyone has access to a public data variable or method—defeating the purpose of encapsulation. Specifier class subclass package world private X package X X protected X X X public X X X X http://www.java2all.com
  • private http://www.java2all.com
  • Superclasses and Subclasses Impact on Access Modifiers: private • When my class inherits from a Superclass, I cannot access the Superclass’s private data variables. Private data is Secret! • In other words, the Subclass cannot automatically reach the private data variables of the Superclass. • A private data variable is accessible only to the class in which it is defined. http://www.java2all.com
  • Objects of type Alpha can inspect or modify the iamprivate variable and can call privateMethod, but objects of any other type cannot.class Alpha{ private int iamprivate; public Alpha( int iam ) { iamprivate = iam; } private void privateMethod() { iamprivate = 2; System.out.println(“” + iamprivate); }} http://www.java2all.com
  • The Beta class, for example, cannot access theiamprivate variable or invoke privateMethod on anobject of type Alpha because Beta is not of type Alpha .class Beta{ public void accessMethod() { Alpha a = new Alpha(); a.iamprivate = 10; // Invalid a.privateMethod(); // Invalid }}• The compiler would complain if you tried this. http://www.java2all.com
  • Can one instance of an Alpha object access theprivate data variables of another instance of anAlpha object? Yes!Objects of the same type have access to oneanother’s private members. http://www.java2all.com
  • package http://www.java2all.com
  • Superclasses and Subclasses Varieties of Access Modifiers: package • If you do not specify the access for either a method or an encapsulated data variable, then it is given the default access: package http://www.java2all.com
  • Superclasses and Subclasses Varieties of Access Modifiers: package • This access allows other classes in the same package as your class to access its data variables as if they were their own. package • This level of access assumes that classes in the same package as your class are friends who won’t harm your class’ data. http://www.java2all.com
  • • Notice that no access modifier is declared. So, iamprivate and method privateMethod both default to package access. • All classes declared in the package Greek, along with class Delta, have access to iamprivate and privateMethod.package Greek;class Delta{ int iamprivate; void privateMethod() { System.out.println(“privateMethod”); }}
  • Superclasses and Subclasses Varieties of Access Modifiers: package package • If you use multiple objects from the same package, they can access each other’s package- access methods and data variables directly, merely by referencing an object that has been instantiated. http://www.java2all.com
  • Superclasses and Subclasses Varieties of Access Modifiers: package package • With package access, other objects in the package don’t have to bother going through the methods. They can get right to the variables. http://www.java2all.com
  • Superclasses and Subclasses• So, when you don’t include any access modifier,you are in fact giving your variable packageaccess. int x; // package access instance variable• Notice, it’s declared neither public norprivate. http://www.java2all.com
  • protected http://www.java2all.com
  • Superclasses and Subclasses • protected allows the class itself, Subclasses and all classes in the same package to access the members. • Generally speaking, protected offers greater access than package access. http://www.java2all.com
  • Superclasses and Subclasses • Use the protected access level when it’s appropriate for a class’s Subclasses to have access to the member, but not for unrelated classes to have access. • protected members are like family secrets— you don’t mind if someone in the family knows— but you don’t want outsiders to know. http://www.java2all.com
  • Superclasses and Subclasses • The Access Modifier protected can be used on either a method or an encapsulated data variable. • protected serves as a middle ground between the private and public access modifier. http://www.java2all.com
  • Superclasses and Subclasses• A Superclass’s protected data variables may beaccessed only by: —methods of the Superclass —methods of the Subclass —methods of other classes in the same package.Or we can summarize: protected members have package access. http://www.java2all.com