ADS-Lecture 02 Using and Defining Classes

Lecture 02 Using and Defining Classes

Compilation

The standard tools for executing Java programs use a two step process:

在这里插入图片描述

This is not the only way to run Java code.

Why make a class file at all?

  • .class file has been type checked. Distributed code is safer.

  • .class files are ‘simpler’ for machine to execute. Distributed code is faster.

  • Minor benefit: Protects your intellectual property. No need to give out source.

Defining and Instantiating Classes

Dog
public class Dog {
    public static void makeNoise(){
        System.out.println("Bark!");
    }
    //Can't run directly, since there is no main method.
}
/** The DogLauncher class will 'test drive' the Dog class. */
public class DogLauncher {
    public static void main(String[] args) {
        Dog.makeNoise(); //Calls a method from another class.
    }
}

As we saw last time:

  • Every method (a.k.a. function) is associated with some class.

  • To run a class, we must define a main method.

    • Not all classes have a main method!
Object Instantiation

Not all dogs are equal!

We could create a separate class for every single dog out there, but this is going to get redundant in a hurry.

public class MayaTheDog {
	public static void makeNoise() {
		System.out.println("arooooooooooooooo!");
   }
}
public class YapsterTheDog {
	public static void makeNoise() {
		System.out.println("awawawwwawwa awawaw");
   }
}

Classes can contain not just functions (a.k.a. methods), but also data.

  • For example, we might add a size variable to each Dog.

Classes can be instantiated as objects.

  • We’ll create a single Dog class, and then create instances of this Dog.

  • The class provides a blueprint that all Dog objects will follow.

Defining a Typical Class (Terminology)
public class Dog {
    /** Instance variable. Can have as many of these as you want. */
    public int weightInPounds;
    
    /** Constructor (similar to a method, but not a method). Determines how to 	   
      * instantiate the class. */
    public Dog(int startingWeight) {
        weightInPounds = startingWeight;
    }
    
    /** Non-static method, a.k.a. Instance Method. Idea: If the method is 	       
      * going to be invoked by an instance of the class (as in the next slide),  	  
      * then it should be non-static. Roughly speaking: If the method needs to    	  
      * use “my instance variables”, the method must be non-static. */
    public void makeNoise() {
        if (weightInPounds < 10) {
            System.out.println("yip!");
        }else if (weightInPounds < 30) {
            System.out.println("bark!");
        }else {
            System.out.println("woof!");
        }
    }
    
}
Instantiating a Class and Terminology
public class DogLauncher {
    public static void main(String[] args) {
        Dog smallDog; 
        // Declaration of a Dog Variable.
        new Dog(20); 
        // Instantiation of the Dog class as a Dog Object.
        smallDog = new Dog(5); 
        // Instantiation and Assignment
        Dog hugeDog = new Dog(150); 
        // Declaration, Instantiation and Assignment.
        smallDog.makeNoise(); 
        //Invocation of the smallDog's makeNoise method.
        hugeDog.makeNoise();
        /** The dot notation means that we want to use a method or variable 		 
          * belonging to hugeDog, or more succinctly, a member of hugeDog. */

    }
}
Arrays of Objects

To create an array of objects:

  • First use the new keyword to create the array.

  • Then use new again for each object that you want to put in the array.

Example:

Dog[] dogs = new Dog[2]; 
// Creates an array of Dogs of size 2.
dogs[0] = new Dog(8);
dogs[1] = new Dog(20);
dogs[0].makeNoise(); // Yipping occurs.

Static vs. Instance Members

Static vs. Non-static I

Key differences between static and non-static (a.k.a. instance) methods:

  • Static methods are invoked using the class name, e.g. Dog.makeNoise();

  • Instance methods are invoked using an instance name, e.g. maya.makeNoise();

  • Static methods can’t access “my” instance variables, because there is no “me”.

Static:

public static void makeNoise() {
    System.out.println("Bark!");
}

This method cannot access weightInPounds!

Invocation:

Dog.makeNoise()

Non-static

public void makeNoise() {
	if (weightInPounds < 10) {
		System.out.println("yipyipyip!");
   	} else if (weightInPounds < 30) {
    	System.out.println("bark. bark.");
	} else { 
        System.out.println("woof!"); 
    }
}

Invocation:

Dog maya = new Dog(100);
maya.makeNoise();
Why Static Methods?

Some classes are never instantiated. For example, Math.

  • x = Math.round(5.6);

    Much nicer than:

    Math m = new Math();
    x = m.round(x);
    

Sometimes, classes may have a mix of static and non-static methods, e.g.

public static Dog maxDog(Dog d1, Dog d2) {
	if (d1.weightInPounds > d2.weightInPounds) {
   		return d1;
	}
	return d2;
}
Static vs. Non-static II

A class may have a mix of static and non-static members.

  • A variable or method defined in a class is also called a member of that class.

  • Static members are accessed using class name, e.g. Dog.binomen.

  • Non-static members cannot be invoked using class name: Dog.makeNoise()(error)

  • Static methods must access instance variables via a specific instance, e.g. d1.

A non-static method can invoke the instance itself using this, which is similar to self in python.

public static void main(String[] args)

One Special Role for Strings: Command Line Arguments
public class ArgsDemo {
	/** Prints out the 0th command line argument. */
	public static void main(String[] args) {
    	System.out.println(args[0]);
	}
}
$ java ArgsDemo hello some args
hello
ArgsSum Exercise

Goal: Create a program ArgsSum that prints out the sum of the command line arguments, assuming they are numbers.

public class ArgsSum {
	/** Prints out the sum of arguments, assuming they are
 	 *  integers. */
	public static void main(String[] args) {
    	int index = 0;
    	int sum = 0;
    	while (index < args.length) {
        	sum = sum + Integer.parseInt(args[index]);
        	index = index + 1;
    	}
    	System.out.println(sum);
	}
}

Using Libraries (e.g. StdDraw, ln)

Java Libraries

There are tons of Java libraries out there.

  • These include (but are not limited to):
  • The built-in Java libraries (e.g. Math, String, Integer, List, Map)
  • The Princeton standard library (e.g. StdDraw,StdAudio, In)
  • Makes various things much easier:
    • Getting user input.
    • Reading from files.
    • Making sounds.
    • Drawing to the screen.
    • Getting random numbers.

As a programmer, you’ll want to leverage existing libraries whenever possible.

  • Saves you the trouble of writing code.

  • Existing widely used libraries are (probably) will probably be less buggy.

  • … but you’ll have to spend some time getting acquainted with the library.

As a programmer, you’ll want to leverage existing libraries whenever possible.

Best ways to learn how to use an unfamiliar library:

  • Find a tutorial (on the web, youtube, etc.) for the library.

  • Read the documentation for the library (Java docs often very good).

  • Look at example code snippets that use the library.

Library Documentation Example

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值