Thinking about java objects, java objects

Source: Internet
Author: User

Thinking about java objects, java objects
Immutable objects and Classes

An object created by an immutable class is an immutable object. To make a class immutable, it must meet the following requirements:

  • All data domains are private.
  • No modifier Method
  • If there is no accessor method, it returns a reference pointing to a variable data domain.

See the following code:

Public class Main {public static void main (String args []) {Student student = new Student (11222333, "John"); java. util. date dateCreatedDate = student. getDateCreated (); dateCreatedDate. setTime (200000) ;}} class Student {private int id; private String name; private java. util. date dateCreated; public Student (int ssn, String newName) {// constructor id = ssn; name = newName; dateCreated = new java. util. date () ;}public int getId () {return id;} public String getName () {return name;} public java. util. date getDateCreated () {return dateCreated ;}}
Variable Scope

Instance variables and static variables of a class are called class variables or data fields. The variables defined within the method are called local variables. Class variables and methods can appear in any order in the class

public class Main{    public static void main(String args[])    {        Foo f = new Foo();        f.p();        }}class Foo {    private int x = 0;    private int y = 0;    public Foo() {            }    public void p() {        int x = 1;        System.out.println("x = " + x);        System.out.println("y = " + y);    }}

Running result:

X = 1
Y = 0

This reference

The keyword "this" refers to the reference name of the calling object. A common usage is to reference the hidden data fields of the class.

class Foo {    int i = 0;    static double k = 0;        void setTime(int i) {        this.i = i;    }    static  void setK(double k) {        Foo.k = k;    }}

Another common method is to let the constructor call another constructor of the same class:

class Circle {    private double radius;        public Circle(double radius) {        this.radius = radius;    }    public Circle() {        this(1.0);    }    public double getArea() {        return this.radius * this.radius * Math.PI;    }}
Class abstraction and Encapsulation

Class abstraction separates the implementation and use of classes, all the methods and data domains that can be accessed from outside the class, and describes how these members are expected to act in a contract called a class.

Instance:

public class Main{    public static void main(String args[])    {        Scanner input = new Scanner(System.in);        System.out.print("Enter yearly interest rate, for example, 8.25: ");        double annualInterestRate = input.nextDouble();        System.out.print("Enter number of years as an integer: ");        int numberOfYear = input.nextInt();        System.out.print("Enter loan amount, for example, 1200000.95: ");        double loanAmount = input.nextDouble();        Loan loan = new Loan(annualInterestRate, numberOfYear, loanAmount);                System.out.printf("The loan was created on %s\n" +                "The monthly payment is %.2f\nThe total payment is %.2f\n",                 loan.getLoanDate().toString(), loan.getMonthlyPayment(),                loan.getTotalPayment());    }}class Loan {    private double annualInterestRate;    private int numberOfYears;    private double loanAmount;    private java.util.Date loanDate;        public Loan() {        this(2.5, 1, 10000);    }    public Loan(double annualInterestRate, int numberOfYears,            double loanAmount) {        this.annualInterestRate = annualInterestRate;        this.numberOfYears = numberOfYears;        this.loanAmount = loanAmount;        loanDate = new java.util.Date();    }    public double getAnnualInterestRate() {        return annualInterestRate;    }    public void setAnnualInterestRate(double annualInterestRate) {        this.annualInterestRate = annualInterestRate;    }    public int getNumberOfYear() {        return numberOfYears;    }    public void setNumberOfYear(int numberOfYears) {        this.numberOfYears = numberOfYears;    }    public double getLoanAmount() {        return loanAmount;    }    public void setLoanAmount(double loanAmount) {        this.loanAmount = loanAmount;    }        public double getMonthlyPayment() {        double monthlyInterestRate = annualInterestRate / 1200;        double monthlyPayment = loanAmount * monthlyInterestRate / (1 -                 (Math.pow((1 / (1 +monthlyInterestRate)), numberOfYears * 12)));        return monthlyPayment;    }    public double getTotalPayment() {        double totalPayment = getMonthlyPayment() * numberOfYears * 12;        return totalPayment;    }    public java.util.Date getLoanDate() {        return loanDate;    }}
Class Design Principles

1. Cohesion

Class should describe a single entity, and all class operations should be logically coordinated to support a consistent goal

If an entity has too many responsibilities, it should be divided into several categories based on its respective responsibilities. For example: String, StringBuffer, StringBuilder

2. Consistency

Follow the standard java programming style and naming conventions. Select a name that contains information for the class, data domain, and method. The name must be consistent.

You should provide a public no-argument constructor for the class to construct the default instance. If you do not want to create class objects, you can declare a private constructor in the class. Example: Math class

3. Encapsulation

Use the private modifier to hide the data, so that you do not have to access it directly and it is easier to maintain.

To make the data domain readable, you only need to provide the get method. If you want data domains to be updated, you should provide the set method.

4. Integrity

In order to be used in a wide range of applications, a class should provide multiple solutions through attributes and methods to meet different needs of users.

For example, String provides more than 40 practical methods.

 


Q: How can I write an object-oriented program in java? If I think about it, what is the sequence of thinking? Do you want to think about the problem from main step by step?

You cannot start thinking from the main method. It is also a process-oriented approach.
Do not think about the execution process of the program, or even do not need to think about the execution process.
First, we should think about the problem model and then design the overall framework of the program, for example, what design patterns are used and what packages are designed
Design top-level class models, interfaces, abstract classes, and so on. Build the overall structure, and then design the specific implementation class...

Java Object-oriented Thinking: Which of the following is more object-oriented and more refined?

My understanding of 1: Merge similar methods. Assume that classes A, B, and C all have A similar method: printXXX ();
At this time, the merging means that even if the common methods of Class A, Class B, and class C are extracted as the common methods of the parent class, it is impossible for ABC to inherit.
But when D, E, F .... N all contain similar methods printXXX () and inherit from them. the problem is that the mutual dependency between a class and multiple classes is enhanced, and there is a conflict with "High Cohesion, low coupling" and the day ABC .. N which class does not need printXXX ()
Is there any need to modify so many types of features, so please do not select 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.