Java class and methods.

Enhancing classes

Overloading Methods is using the same method name for multiple methods.

Data scope, When declare a variable within a block{},you cannot access it outside the block{}

 Arrays: Integers, doubles, char, String

  • String[] str=new String[]
  • int[] scores=new int[10]
  • char[] letter={‘a’,’b’}

 

Instantiable Class

Two type of class

  • Driver programs: a class contains a main method
  • Collections of constants or methods, create object.

String defines String objects String str;

Objects:

  • State instance variables
  • Behaviors instance methods

Write a driver program

  • With a main method
  • Constructor to create an object
  • Utilizes the objects methods

Write a class definition

  • Define instance variables
  • Define a Constructor
  • Define instance methods

 Instantiable class

  • state: defined by instance variables
  • behaviors: defined by instance methods
  • Constructor

Driver programmer

public class TestCounter

{

            public static void main (String [] args)

            {

           //create Counter object

          // call click method

          //get number of clicks

          // print number of clicks

            }

}

 

public class Counter

{

            define instance variable

            define constructor

            {

            }   

            define click method

            {

            }

            define get number of clicks method

            {

             }

}

 

 

Constructor

  • A constructor is a special method that contain instructions to setup a newly created object
  • Same name as class
  • Similar to a method
  • No return a value(no void)
  • Sets the initial values of instance variables
  • Invoked by “new”

 

The most common error is: instance variables is private, The  makes access to them available only by methods within the class

 

The driver program cannot access instance variables directly.

 

Instance variables ---------Private

Constrictors-----------------Public

Methods ---------------------Public

 

Overloading constrictors

Die die1=new Die()

Die die2=new Die()

 

Object-Oriented Analysis

  • So an initial analysis of a banking system might reveal:
  • Nouns ie suggested classes in the specification for a banking system:
    • Customer
    • Account
  • Verbs ie suggested methods in the specification for a banking system:
    • Open (an account)
    • Deposit (money into an account)
    • Withdraw (money from an account)
    • Close (an account)
    •  

Categories of Methods

         Most instance methods fall into one of several categories:

        Manager methods

        Implementor methods

        Access methods

Manager Methods

  • Initialise objects

        Constructors

        Having additional constructors makes a class more useful.

 

Implementor Methods

  • Implementor methods represent useful operations that can be performed on instances of the class.
  • Implementor methods usually change the state of an object
  • The Account class  implementor methods:

open,

deposit,

withdraw,

 close.

 

Access Methods

         For access to instance variables, the choice is:

        provide instance methods or

        make the variables public (but this violates good object orientation)

         Accessors (or getters)

        methods that return the value of a private variable.

        by convention, names of getters start with the word get

         Mutators (or setters)

        methods that change the value of a private variable.

        by convention, names of setters start with the word set

 

This: is used to refer to the object that invoked the method variables

 

Instance variables

         belong to an object

        are created when an object is constructed

        exist as long as the object exists

         each object has its own copy

        that’s what allows objects to be different

         are automatically initialised (if not explicitly set in a constructor),

        zero for numeric and char variables

        false for boolean variables

        null for reference type variables

         every instance variable should be initialised in a constructor

 

The static Modifier

         We have used methods that do not require objects

         eg methods of Math class

         These static or class methods are invoked through the class name - not through an object name

         To make a method static, we apply the static modifier to the method definition

                        static double sqrt (double num)

         And call the method by the class name

                        System.out.print (“sq rt of 9: “ + Math.sqrt(9))

  • The static modifier can be applied to variables as well
  • It associates a variable with the class rather than an object
  • They are declared with the word static
  • Normally, each object has its own data space
  • If a variable is declared as static, only one copy of the variable exists
  • Eg in the Account class a useful class variable may be
  • private static double totalDeposits;

         All objects created from the class share access to the static variable

         Changing the value of a static variable in one object changes it for all others

         Eg to allocate a unique asset number every time a new asset object is created

        A static variable could hold the last used asset number

        Any new asset could increment this number by 1

 

Inheritance

         enhances software design and promotes reuse

         deriving new classes from existing ones

         the protected modifier

         Overriding

 

Genetic inheritance

         Genetic inheritance - facts

        Eg Your blood type, hair colour, height, body shape

        Many facts about you (ie, your instance data) are inherited

         Genetic inheritance – behaviour

        eg Sports and leisure interests, loudly or quietly spoken

        Much of your behaviour (ie your methods) are inherited

         Many objects have similarities to other objects

        Eg cars and trucks are similar and examples of vehicles

         A class (car) can have a ‘parent’ (vehicle) from which it inherits some of its data and behaviour

         Inheritance allows a software developer to derive a new class from an existing one   

         The existing class is called the parent class, base class or superclass

         The derived class is called the child class or subclass

         As the name implies, the child inherits characteristics (the methods and data) of the parent

 

Deriving Subclasses

         In Java, we use the reserved word extends to establish an inheritance relationship

 

            public class EmployeeWithCar extends Employee

            {

                           // class contents

            }

           

Advantages of inheritance

         Saves time

        reusing data and methods that already exist

        makes programs easier to write

         Reduces errors

        methods have already been used and tested

 

Writing Subclass Constructors

         A subclass doesn’t inherit constructors from its superclass

         The constructor for the SavingsAccount class will need to initialize both the balance and interestRate variables

        But the superclass instance variables are likely to be private so they cannot be referenced directly from the subclass

 

         The hard part of writing a constructor for a subclass is initializing the variables that belong to the superclass

 

Subclass constructors

         Writing constructors for a subclass is the same, except for initialisation of superclass variables (if private)

 

                        public SavingsAccount (double initialBalance,  double initialRate)

                        {

                                    balance = initialBalance;      //ERROR

                                    interestRate = initialRate;

                        }

 

         As balance was declared as private in the Account class this will not compile – the SavingsAccount class has no access to it

 

The super Reference

         A child’s constructor is responsible for calling the parent’s constructor

         The first line of a child’s constructor should use the super reference to call the parent’s constructor

         To access a superclass private instance variable we need to use a superclass method…or in this case constructor

         We want to use the parent's constructor to set up the "parent's part" of the object

         The super reference can be used to refer to the parent class, and is often used to invoke the parent's constructor

         The first line of a child’s constructor uses the super reference to call the parent’s constructor

 

 Invoking the superclass constructor

          The SavingsAccount constructor invokes the Account constructor using the word super

 

                        public SavingsAccount (double initialBalance,  double initialRate)

                        {

                                    super (initialBalance);    //invoke Account constructor

                                    interestRate = initialRate;

                        }

         The account constructor will initialise the balance variable to the value stored in initialBalance

 

 

Superclass constructor parameters

         The subclass constructor must provide all the parameters required by the superclass constructor in order eg.

 

   public Account (String owner, int account, double initial)                 // superclass constructor

   {

       name = owner;

       acctNumber = account;

       balance = initial;

   }

 

  public SavingsAccount(String owner, int account, double initial, double rate)  // subclass                                                                                                             //constructor

  {

        super (owner, account, initial);

        interestRate = rate;

  }

 

Writing Subclass Constructors

         If a subclass constructor fails to include super, the compiler will automatically insert super(); at the beginning of the constructor.

         If a subclass has no constructors at all, the compiler will create a no-arg constructor that contains super(); but no other statements.

        

 

Controlling Inheritance

         Visibility modifiers determine which class members get inherited and which do not

         Variables and methods declared with public visibility are inherited

         Those with private visibility are not actually inherited in that we need to use the superclass constructor and methods to access them

 

         But public variables violate our goal of encapsulation!

 

The protected Modifier

         There is a third visibility modifier that helps in inheritance situations: protected

 protected  behaves the same as private within a class but allows a member of a base class to be inherited into the child class

private            can only be accessed in the same class

protected        can only be accessed in the same class or in a subclass

public  can be accessed in any class

 

protected versus private

         Declaring instance variables protected exposes them to all subclasses

         This is a potentially unlimited number and may weaken an object-oriented goal of encapsulation

         If a subclass needs access to these variables it should be able to call a getter or setter method of the superclass

 

         We will not use protected variables

         Always declare instance variables private

 

Methods available to a subclass

         Inherit methods from the superclass

        superclass methods can be applied to subclass objects

                                    account1.deposit(200.00);

 

         Define new methods

                        public void setInterestRate(double  rate);

 

         Override methods from the superclass

        ie specify a method with the same signature (that is the same name, return type and parameter types) in the subclass

        this method defined in the subclass will take precedence

        Use super to call an overridden method

 

Using the right method

         Java looks first in the class of the calling object, then in the class’s superclass, then its superclass etc

         Consider the following statement:

                         account1.deposit(500.00)

         Java first looks for the deposit method in the SavingsAccount class, then in the Account class.

        

 

Overloading vs. Overriding

         Don't confuse the concepts of overloading and overriding

         Overloading deals with multiple methods in the same class with the same name but different signatures

         Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature

         Overloading lets you define a similar operation in different ways for different data

         Overriding lets you define a similar operation in different ways for different object types

 

 

Java method Invoked Methods

         Static(public static)(public static account)

            same class(object.method)(bank.account)

         none of static (public account)

account acc1=new account()

acc1.deposit

         overloading

different class

Overloading deals with multiple methods in the same class with the same name but different signatures

import account;(if not same folder)

overloading constructors

Overloading lets you define a similar operation in different ways for different data

 

         overriding

Inheritance (extends employees)

no inherit

constructors

from super_class

            Overriding deals with two methods, one in a parent class and one in a child class,               

            that have the same signature

Overriding lets you define a similar operation in different ways for different object types

 

 

你可能感兴趣的:(技术类)