Java Workshop #4

Organizing code: packages and access modifiers

Recap

  • Classes and objects
  • Methods
  • Inheritance

Classes and objects(1)

  • Classes are the building blocks of a java program
  • Classes contain the definition of what a program should do
  • An object is an instance of a class in the program
  • You can have multiple objects of the same class

Classes and objects(2)

¡Get your class right!

  • The name of the class should be the same as the name of the file
  • In order to start a java program we need to have a class with a main() method
  • The code of a class is contained in curly braces: {}

The simplest example:

A class contains:

  • Class Name
  • Fields/variables - used for storing data 
  • Methods (functions/procedures) - used for manipulating data
  • The fields and methods of a class are called class members

Create new project: Drawing

Remember to check "Create project from template" so that the first class is already created for you

Create a new class: Shape

Let's give it a shape

public class Shape {
    
    public double area(){
        return 0;
    }
    
    public void printInfo(){
        System.out.println("just some random shape");
    }
}
  • Add the following code to the Shape class

Let's see how the class behaves

public class Main {

    public static void main(String[] args) {
	    Shape randomShape = new Shape();

	    randomShape.printInfo();

	    System.out.println("The are of the shape is: " + randomShape.area());
    }
}
  • Add the following code to the Main class and run the program

Remember constructors?

Shape randomShape = new Shape();
  • Constructors are used to tell the program to create a new object of a specific class
  • A constructor is a special method that belongs to the class 
  • The purpose of a constructor is to initialize fields

And methods?

public double area(){}

A method has:

  • an access modifier: public
  • a return type: double
  • a name: area
  • 0 or more arguments
  • a body: always between {}

Inheritance

  • Classes can be derived from other classes, inheriting fields and methods from those classes
  • Constructors cannot be inherited as they are not class members
  •  A class that is derived from another class is called a subclass (or a derived class or a child class)
  •  The class from which the subclass is derived is called a superclass (or a base class or a parent class)

Next:

We will create the subclasses Circle and Rectangle that inherit from the Shape class

Create the new class Circle and add the following code:

public class Circle extends Shape{
    private double radius;
    private final double PI = Math.PI;

    public Circle(int r){
        radius = r;
    }

    public double area() {
        //Math.pow(radius, 2) = radius * radius
        return PI * Math.pow(radius, 2);
    }

    public void printInfo(){
        System.out.println("I am a circle and know the value of PI: " + PI);
    }
}

Create the new class Rectangle and add the following code:

public class Rectangle extends Shape{
    private double width;
    private double length;

    public Rectangle(int w, int l){
        width = w;
        length = l;
    }

    public double area(){
        return width * length;
    }
}

Modify the Main class in order to create 2 new objects besides the previously created Shape object:

   public static void main(String[] args) {
	    Shape randomShape = new Shape();
	    randomShape.printInfo();
	    System.out.println("The are of the shape is: " + randomShape.area());
	    System.out.println(); //this is added only as a separator to clarify the output

	    Circle circle = new Circle(4);
	    circle.printInfo();
	    System.out.println("The are of the circle is: " + circle.area());
	    System.out.println();

	    Rectangle rectangle = new Rectangle(4, 5);
	    rectangle.printInfo();
	    System.out.println("The are of the rectangle is: " + rectangle.area());
    }

Do you see the difference in output?

Inheritance

  • Circle and Rectangle inherit from Shape
  • Shape is a superclass
  • Circle and Rectangle are subclasses

 

  • IS A defines Inheritance
  • A circle IS A shape
  • A rectangle IS A shape

Let's get to the new stuff

  • Packages

  • Access modifiers

Packages

Check any of your classes from the Drawing project. You will see all have the first following line:

package com.base;

It defines the package the class is part of.

 

It is the first line of code in any class.

So what are packages?

They are a way to organize your code in order to:

  • Prevent name collisions
  • Make your classes easier to find

Avoiding name collisions

  • It is very probable that 2 developers name their classes the same.
  • But the "real" name of a class is the one containing also the package name
  • The Circle class is actually called com.base.Circle
  • com.base.Circle is called a fully-qualified name
  • In order to avoid name collisions there are some guidelines each developer should follow when naming their packages

Package naming guidelines

  • Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
  • Companies use their reversed Internet domain name to begin their package names - for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.
  • Packages in the Java language itself begin with java. or javax.

     

Let's create a new package

It's the same as creating a new class

Add some code to the package

  • Name your package com.shape
  • Move the classes Shape, Circle and Rectangle in the newly created package
  • What happened to the first line of each of  these classes?
  • What happened to the Main class?

Modifications in the Main class

The Main class was modified automatically and the following code was added:

import com.shape.Circle;
import com.shape.Rectangle;
import com.shape.Shape;

These 3 lines of code are called import statements

Import statements

  • In order to use a class from another package the class or the whole package needs to be imported
  • Import statements have to be added exactly after the package declaration

Comment out the import statements in the Main class

//import com.shape.Circle;
//import com.shape.Rectangle;
//import com.shape.Shape;

What is happening? Can you still compile and run your project?

Import an entire package

import com.shape.Circle;
import com.shape.Rectangle;
import com.shape.Shape;

Replace the import statements:

with:

import com.shape.*;

Access levels

  • public
  • private
  • protected
  • default

Access modifiers

  • public
  • private
  • protected

 

default is what you get when there is no access modifier

Access levels

public

  • use for classes, constants, methods that you want to expose to other code and constructors

In our examples all our class members have been public, but this is not good practice

private

  • use for all instance variables and methods that you don't want other classes to call

Make class Circle private

What happens? Check the messages from your IDE. Can you still compile the code?

The IDE knows

Make the method area in class Shape private

default

  • default means a class isn't explicitly declared as public
  • a default class can only be accessed only by classes in the same package

Remove the access modifier of class Shape.

What happens to the code in the Main class?

protected

  • is identical to default, but it allows subclasses to inherit the protected thing even if the subclasses are outside the package of the superclass they extend
  • Make printInfo in class Shape protected
  • Move the classes Circle and Rectangle in the com.base package

Is the project still compiling? Why?

Made with Slides.com