Beginning classes in java

Creating Classes

To run our java programs we had to create something called a class. Inside of this class we had something called a method. Up until this point we have been using the rebuilt class and method that eclipse created for us. Now we will learn to create our own.

A class can be seen as blueprint for an object. When we create an object such as a String we are creating what’s known as an instance of the class String. Somewhere in Java there exists a class called String that we used to create a new String object. The same can be said about other objects like an ArrayList. When we create a new ArrayList we are creating an instance of the class ArrayList and somewhere in Java there is a class called Arrayist.

Essentially a class defines the properties and attributes associated with objects that belong to it. Objects of the Integer class can be added/divided/multiplied etc. While objects of the Scanner class can be used to read in input. Each class has different properties.

So up until now we have been using classes without even knowing it! These classes are built into Java and were coded by other people.

Now we will work on creating our own classes and objects.

Class Names

Eclipse makes it fairly easy to create a class, we can do so by right clicking on our package and clicking New > Class.

Читайте также:  Python raise new exception

When we create a class we need to follow a few rules.

  1. The class name must begin with a capital (Ex. Valid Class: Person, Invalid Class: person )
  2. The class name must match the name of the file it is written in (Ex. Class Name: Tim, File Name: Tim.java)

Access Modifiers

In java we have something called access modifiers. These are words like: public, private and protected that allow you to define what scope a specific method, class or variable is accessible in.

Private: For methods and variables this means they are only accessible in the current class. In other words, they cannot be modified from outside of that class. A private class however means it is only accessible within the current package (not super important for our purposes).

Public: For methods and variables this means they are accessible from inside and outside of the class. Meaning you can change them from anywhere! A public class is accessible anywhere (kind of).

Protected: This is a special access modifier that we will talk more about later. It’s very similar to private but allows for whats known as a child class or a derived class to access the parents class attributes or methods.

Attributes

Most of our classes contain something called attributes, you may also hear these referred to as instance variables. These are variables that are specific to an instance of the class or an object of that class type. We define them using the private access modifier at the top of our class definition. You can think of these as the information associated with each object. They will be different for each instance of the class.

In the example below you can see an example of two attributes.

public class Dog   private String name; private int age; > 

Notice that I don't declare the values of these attributes but I simply define them.

Constructor

The constructor is a special kind of method that is called immediately upon creating a new object or instance of the class.

The constructor is where we construct or setup the object so it is ready to be used. We typically set all of our attribute values and call any necessary methods. To create a constructor we create a public method that is the same name of our class. We then can choose any necessary parameters that must be passed to our constructor. This will be the information that we need to pass every time we create a new instance of the class.

public class Dog   private String name; private int age; public Dog(String name, int age)  this.name = name; this.age = age; > > 

Now it's time to talk about this. The keyword "this" is what we used to access our attributes. You can see that in the above code we are setting "this" objects attributes to be the passed values.

Methods

A method is like a function. It is something that can be called on an instance of a class. When we create a method we need a few things.

  • The access modifier
  • The name of the method
  • The return type
  • The parameters

In the below example these values are as follows: Access Modifier: public Method Name: speak Return Type: void Parameters: None

public class Dog   private String name; private int age; public Dog(String name, int age)  this.name = name; this.age = age; > // This is a method public void speak()  Sytsem.out.println("I am " + this.name + "and I am " + this.age + " years old") > > 

Creating Objects

Now that we have created a simple class it's time to create some instances of it (otherwise known as objects). We are going to do this from our static void main method inside are other file.

Since we added two parameters to our Dog class constructor we need to pass two values whenever we create a new Dog.

public class Main   public static void main(String[] args)  Dog dog1 = new Dog("Tim", 5); // This is how to create new instance of the dog class Dog dog2 = new Dog("Joe", 7); // Here we create another dog, this time with name "Joe" and age 7 > > 

If we call the methods on our dogs we can get some information to print to the console when we run the program.

public class Main   public static void main(String[] args)  Dog dog1 = new Dog("Tim", 5); Dog dog2 = new Dog("Joe", 7); dog1.speak() // calling the speak method dog2.speak() > > 

Getters and Setters

Now that we've seen a basic example of methods lets talk getters and setters. Our last method simply printed our some information to the screen. This is great but sometimes we actually want to use a method to change or get the attributes associated with our object. To do this we need to create the following:

Getters: These are used to GET a value from our object. For example we want to get the age of our dog, so we create a getter method to do that.

Setter: These are used to SET or change a value associated with our object. For example we many want to set our dogs age.

Below you can see some examples of getters and setters on our dog class..

public class Dog  private String name; private int age; public Dog(String name, int age)  this.name = name; this.age = age; > public void speak()  System.out.println("I am " + this.name + "and I am " + this.age + " years old"); > // Getters public int get_age() return this.age; > public String get_name() return this.name; > // Setters public void set_age(int age)  this.age = age; > public void set_name(String name)  this.name = name; > > 

Источник

Lesson: A Closer Look at the "Hello World!" Application

Now that you've seen the "Hello World!" application (and perhaps even compiled and run it), you might be wondering how it works. Here again is its code:

The "Hello World!" application consists of three primary components: source code comments, the HelloWorldApp class definition, and the main method. The following explanation will provide you with a basic understanding of the code, but the deeper implications will only become apparent after you've finished reading the rest of the tutorial.

Source Code Comments

/** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp < public static void main(String[] args) < System.out.println("Hello World!"); // Display the string. > >

Comments are ignored by the compiler but are useful to other programmers. The Java programming language supports three kinds of comments:

/* text */ The compiler ignores everything from /* to */ . /** documentation */ This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */ . The javadoc tool uses doc comments when preparing automatically generated documentation. For more information on javadoc , see the Javadoc™ tool documentation . // text The compiler ignores everything from // to the end of the line.

The HelloWorldApp Class Definition

/** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp public static void main(String[] args) < System.out.println("Hello World!"); // Display the string. >> 

As shown above, the most basic form of a class definition is:

The keyword class begins the class definition for a class named name , and the code for each class appears between the opening and closing curly braces marked in bold above. Chapter 2 provides an overview of classes in general, and Chapter 4 discusses classes in detail. For now it is enough to know that every application begins with a class definition.

The main Method

/** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp < public static void main(String[] args) System.out.println("Hello World!"); //Display the string. > >

In the Java programming language, every application must contain a main method whose signature is:

public static void main(String[] args)

The modifiers public and static can be written in either order ( public static or static public ), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".

The main method is similar to the main function in C and C++; it's the entry point for your application and will subsequently invoke all the other methods required by your program.

The main method accepts a single argument: an array of elements of type String .

public static void main(String[] args)

This array is the mechanism through which the runtime system passes information to your application. For example:

Each string in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. For example, a sorting program might allow the user to specify that the data be sorted in descending order with this command-line argument:

The "Hello World!" application ignores its command-line arguments, but you should be aware of the fact that such arguments do exist.

System.out.println("Hello World!");

uses the System class from the core library to print the "Hello World!" message to standard output. Portions of this library (also known as the "Application Programming Interface", or "API") will be discussed throughout the remainder of the tutorial.

Источник

Classes

The introduction to object-oriented concepts in the lesson titled Object-oriented Programming Concepts used a bicycle class as an example, with racing bikes, mountain bikes, and tandem bikes as subclasses. Here is sample code for a possible implementation of a Bicycle class, to give you an overview of a class declaration. Subsequent sections of this lesson will back up and explain class declarations step by step. For the moment, don't concern yourself with the details.

public class Bicycle < // the Bicycle class has // three fields public int cadence; public int gear; public int speed; // the Bicycle class has // one constructor public Bicycle(int startCadence, int startSpeed, int startGear) < gear = startGear; cadence = startCadence; speed = startSpeed; >// the Bicycle class has // four methods public void setCadence(int newValue) < cadence = newValue; >public void setGear(int newValue) < gear = newValue; >public void applyBrake(int decrement) < speed -= decrement; >public void speedUp(int increment) < speed += increment; >>

A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:

public class MountainBike extends Bicycle < // the MountainBike subclass has // one field public int seatHeight; // the MountainBike subclass has // one constructor public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) < super(startCadence, startSpeed, startGear); seatHeight = startHeight; >// the MountainBike subclass has // one method public void setHeight(int newValue) < seatHeight = newValue; >>

MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it (mountain bikes have seats that can be moved up and down as the terrain demands).

Источник

Оцените статью