Java Tutorial/Class Definition/Defining Class

Материал из Java эксперт
Перейти к: навигация, поиск

Checking whether the object referenced was of type String

   <source lang="java">

class Animal {

 public Animal(String aType) {
   type = aType;
 }
 public String toString() {
   return "This is a " + type;
 }
 private String type;

} public class MainClass {

 public static void main(String[] a) {
   Animal pet = new Animal("a");
   if (pet.getClass() == Animal.class) {
     System.out.println("it is an animal!");
   }
 }

}</source>



it is an animal!


Class declaration with a method that has a parameter

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  { 
     GradeBook myGradeBook = new GradeBook(); 
     String courseName = "Java ";
     myGradeBook.displayMessage( courseName );
  }

} class GradeBook {

  public void displayMessage( String courseName )
  {
     System.out.printf( "Welcome to the grade book for\n%s!\n", 
        courseName );
  }

}</source>



Welcome to the grade book for
Java !


Class declaration with one method

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  { 
     GradeBook myGradeBook = new GradeBook(); 
     myGradeBook.displayMessage(); 
  }

} class GradeBook {

  public void displayMessage()
  {
     System.out.println( "Welcome to the Grade Book!" );
  }

}</source>



Welcome to the Grade Book!


Class that contains a String instance variable and methods to set and get its value

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  { 
     GradeBook myGradeBook = new GradeBook(); 
     System.out.printf( "Initial course name is: %s\n\n",myGradeBook.getCourseName() );
     String theName = "Java";
     myGradeBook.setCourseName( theName ); // set the course name
     myGradeBook.displayMessage();
  }

} class GradeBook {

  private String courseName; // course name for this GradeBook
  // method to set the course name
  public void setCourseName( String name )
  {
     courseName = name; // store the course name
  }
  // method to retrieve the course name
  public String getCourseName()
  {
     return courseName;
  }
  // display a welcome message to the GradeBook user
  public void displayMessage()
  {
     System.out.printf( "Welcome to the grade book for\n%s!\n", 
        getCourseName() );
  }

}</source>



Initial course name is: null
Welcome to the grade book for
Java!


Class with a constructor to initialize instance variables

   <source lang="java">

public class MainClass {

  public static void main( String args[] ) 
  {
     Account account1 = new Account( 50.00 ); // create Account object
     Account account2 = new Account( -7.53 ); // create Account object
     System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() );
     System.out.printf( "account2 balance: $%.2f\n\n", account2.getBalance() );
     
     double depositAmount; // deposit amount read from user
     depositAmount = 10.10;
     account1.credit( depositAmount ); // add to account1 balance
     System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() );
     System.out.printf( "account2 balance: $%.2f\n\n", account2.getBalance() );
     depositAmount = 12.12; 
     account2.credit( depositAmount ); // add to account2 balance
     System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() );
     System.out.printf( "account2 balance: $%.2f\n", account2.getBalance() );
  }

} class Account {

  private double balance; // instance variable that stores the balance
  // constructor  
  public Account( double initialBalance )
  {
     if ( initialBalance > 0.0 ) 
        balance = initialBalance; 
  }
  public void credit( double amount )
  {      
     balance = balance + amount;
  }
  public double getBalance()
  {
     return balance;
  }

}</source>



account1 balance: $50.00
account2 balance: $0.00
account1 balance: $60.10
account2 balance: $0.00
account1 balance: $60.10
account2 balance: $12.12


Creating Objects of a Class

   <source lang="java">

class Sphere {

 double radius; // Radius of a sphere
 Sphere() {
 }
 // Class constructor
 Sphere(double theRadius) {
   radius = theRadius; // Set the radius
 }

} public class MainClass {

 public static void main(String[] arg){
   Sphere sp = new Sphere();
   
 }

}</source>





Defining Classes: A class has fields and methods

   <source lang="java">

public class MainClass {

 private int aField;
 public void aMethod() {
 }

}</source>





Fields

  1. Fields are variables.
  2. They can be primitives or references to objects.

For example, the Employee class has two fields, age and salary.



   <source lang="java">

public class Employee{

 int age;
 int salary

}</source>



  1. Field names should follow the camel naming convention.
  2. The initial of each word in the field, except for the first word, is written with a capital letter.
  3. For example: age, maxAge, address, validAddress, numberOfRows.


Specifying initial values in a class definition

   <source lang="java">

class A {

 A(int marker) {
   System.out.println("Bowl(" + marker + ")");
 }
 void f(int marker) {
   System.out.println("f(" + marker + ")");
 }

} class B {

 static A a = new A(1);
 B() {
   System.out.println("Table()");
   staticA.f(1);
 }
 void f2(int marker) {
   System.out.println("f2(" + marker + ")");
 }
 static A staticA = new A(2);

} class C {

 A a = new A(3);
 static A staticA = new A(4);
 C() {
   System.out.println("Cupboard()");
   staticA.f(2);
 }
 void f3(int marker) {
   System.out.println("f3(" + marker + ")");
 }
 static A staticA2 = new A(5);

} public class MainClass {

 public static void main(String[] args) {
   System.out.println("Creating new Cupboard() in main");
   new C();
   System.out.println("Creating new Cupboard() in main");
   new C();
   t2.f2(1);
   t3.f3(1);
 }
 static B t2 = new B();
 static C t3 = new C();

}</source>



Bowl(1)
Bowl(2)
Table()
f(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
f2(1)
f3(1)


What Is a Java Class?

Classes are the fundamental building blocks of a Java program. You can define an Employee class as follows:



   <source lang="java">

class Employee {

 int age;
 double salary;

}</source>



  1. By convention, class names capitalize the initial of each word.
  2. For example: Employee, Boss, DateUtility, PostOffice, RegularRateCalculator.
  3. This type of naming convention is known as Pascal naming convention.
  4. The other convention, the camel naming convention, capitalize the initial of each word, except the first word.
  5. Method and field names use the camel naming convention.