SlideServe
Menu
Préférences
© SlideServe · v2026

Understanding Java Constructors and Local Variables in Programming

kitra-wells avatar
29 diapositives · 465 Views · Nov 21, 2014

This session in COMP 110 focuses on the critical topic of constructors in Java programming, including how they are utilized to create and initialize objects. Key concepts discussed include the significance of the main method, the output behavior of local versus instance variables, and practical examples highlighting the use of multiple constructors. The session also addresses common errors encountered, such as the `java.lang.NoSuchMethodError`, and emphasizes the importance of proper data initialization to prevent unexpected behavior in programs. Don't forget: Lab 5 is due October 31 at 2 PM!

Understanding Java Constructors and Local Variables in Programming - slide 1
01 / 29Understanding Java Constructors and Local Variables in Programming
1 / 17

Télécharger la présentation

Understanding Java Constructors and Local Variables in Programming
Une image / un lien ci-dessous est fourni (tel quel) pour télécharger la présentation

Politique de téléchargement : le contenu du site vous est fourni TEL QUEL pour votre information et votre usage personnel ; il ne peut être vendu, concédé sous licence ni partagé sur d’autres sites sans l’accord de son auteur.Le contenu vous est fourni TEL QUEL, pour votre information et votre usage personnel uniquement. Téléchargez la présentation en cliquant sur ce lien. Lors du téléchargement, si vous ne parvenez pas à télécharger une présentation, l’éditeur a peut-être supprimé le fichier de son serveur.Pendant le téléchargement, si vous ne parvenez pas à obtenir une présentation, le fichier a peut-être été supprimé par l’éditeur.

F I N

Plus de contenu associé

Transcription de la présentation
  1. COMP 110Constructors Luv Kohli October 13, 2008 MWF 2-2:50 pm Sitterson 014

  2. Announcements • Program 3 assigned today, due October 31, 2pm • Ivan Sutherland talk today, 4pm, Sitterson Hall 011

  3. Questions? • How is Lab 5 going?

  4. Today in COMP 110 • A couple of notes • Friday’s in-class exercise • Constructors

  5. Running a Java program • Make sure you are running the program that has a main method in it • Otherwise, you will get this: java.lang.NoSuchMethodError: main Exception in thread "main"

  6. Local variables • What does the greet() method output? publicclass Example { private String str = “hello”; publicvoid doStuff() { String str = “goodbye”; } publicvoid greet() { doStuff(); System.out.println(str); } } • Outputs hello. Why? • doStuff() uses local variable str, not instance variable str

  7. Local variables • What does the greet() method output? publicclass Example { private String str = “hello”; publicvoid doStuff() { str = “goodbye”; } publicvoid greet() { doStuff(); System.out.println(str); } } • Outputs goodbye. Why? • Make sure you understand this for step 1 of Lab 5!

  8. Creating a new instance publicclass AnotherExample { private Student jack; publicvoid myMethod() { jack = new Student(); jack.setName(“Jack Smith”); jack.setAge(19); } }

  9. Friday’s in-class exercise

  10. The perils of incorrectly initialized data

  11. Spirit of Kansas crash, Feb. 23, 2008 • http://www.youtube.com/watch?v=_ZCp5h1gK2Q • After heavy rains, water affected air-data sensors • These sensors feed angle of attack and yaw data to flight-control system • Water distorted preflight readings in 3 of the plane’s 24 sensors • Caused flight-control system to make an erroneous correction, making the plane stall and crash

  12. Constructors • Create and initialize new objects • Special methods that are called when creating a new object Student jack = new Student(); Calling a constructor

  13. Creating an object Create an object jack of class Student Student jack = new Student(); Scanner keyboard = new Scanner(System.in); Create an object keyboard of class Scanner Assign memory address of object to variable Return memory address of object Create an objectby calling a constructor

  14. Constructors • Can perform any action you write into a constructor’s definition • Meant to perform initializing actions • For example, initializing values of instance variables

  15. Similar to mutator methods • However, constructors create an object in addition to initializing it • Like methods, constructors can have parameters

  16. Example: Pet class publicclass Pet { private String name; privateint age; privatedouble weight; public Pet() { name = “No name yet.”; age = 0; weight = 0; } public Pet(String initName, int initAge, double initWeight) { name = initName; age = initAge; weight = initWeight; } } Default constructor

  17. Example: Pet class, setPet method publicvoid setPet(String newName, int newAge, double newWeight) { name = newName; age = newAge; weight = newWeight; }

  18. A closer look public Pet(String initName, int initAge, double initWeight) { name = initName; age = initAge; weight = initWeight; } Same name as class name Parameters Body No return type

  19. Initializing instance variables • Constructors give values to all instance variables • Even if you do not explicitly give an instance variable a value in your constructor, Java will give it a default value • Normal programming practice to give values to all instance variables

  20. Default constructor • Constructor that takes no parameters public Pet() { name = “No name yet.”; age = 0; weight = 0; } • Java automatically defines a default constructor if you do not define any constructors

  21. Default constructor • If you define at least one constructor, a default constructor will not be created for you

  22. Several constructors • You can have several constructors per class • They all have the same name, just different parameters

  23. Example: Pet class publicclass Pet { private String name; privateint age; privatedouble weight; public Pet() { name = “No name yet.”; age = 0; weight = 0; } public Pet(String initName, int initAge, double initWeight) { name = initName; age = initAge; weight = initWeight; } }

  24. Calling a constructor Pet myPet; myPet = new Pet(“Frostillicus”, 3, 121.5); • You cannot use an existing object to call a constructor: myPet.Pet(“Fang”, 3, 155.5); // invalid!

  25. Change an object using mutators myPet.setPet(“Fang”, 1, 155.5);

  26. Calling methods from constructors • Just like calling methods from methods public Pet(String initName, int initAge, double initWeight) { setPet(initName, initAge, initWeight); } public void setPet(String newName, int newAge, double newWeight) { name = newName; age = newAge; weight = newWeight; }

  27. Calling methods from constructors • Can cause problems when calling public methods • Problem has to do with inheritance, chapter 8 • Another class can alter the behavior of public methods • Can solve problem by making any method that constructor calls private

  28. Example: Pet class publicclass Pet { private String name; privateint age; privatedouble weight; public Pet(String initName, int initAge, double initWeight) { set(initName, initAge, initWeight); } public void setPet(String newName, int newAge, double newWeight) { set(newName, newAge, newWeight); } private void set(String newName, int newAge, double newWeight) { name = newName; age = newAge; weight = newWeight; } }

  29. Wednesday • Talk about Lab 5 • More about constructors • Static variables and methods