Presentation on theme: "OO Programming in Java Objectives for today: Constructors Method Overriding & Overloading Encapsulation."— Presentation transcript:
OO Programming in Java Objectives for today: Constructors Method Overriding & Overloading Encapsulation
OO Concepts Constructors Constructors are special methods used to prepare newly created objects for use. They are commonly used to initialize fields to specific values when the object is created. The following are examples of calling constructors: Car myCar = new Car( ); String theString = new String(“Hello World”); Integer theInt = new Integer(10);
OO Concepts Constructors: You can create multiple constructors for one class as long as you define different arguments for each constructor. By creating multiple constructors you can construct your objects in different ways by providing the object with different arguments. This technique is called constructor overloading.
OO Concepts Constructors and Inheritance If you define your own super class with a constructor you should define a similar constructor in any subclass you may create. For every constructor you build in a super class, you should build a constructor in the sub class that accepts the same argument types. The constructor you build should make a call to the super class constructor using the “super” keyword to initialize the fields at that level. “Exam”
Method Overriding & Overloading Method Overriding When you create a subclass, that class inherits all the methods and fields of its superclass by default. The subclass can redefine the inherited methods, as well as define new methods. When you redefine a method in a subclass of the same signature of the superclass you override the superclass method. Method overriding is creating a method in a subclass with the same signature, to give your method some additional or different behavior.
Method Overriding & Overloading Method Overriding The signature of a method includes the following: The name of the method. The return type. The number of arguments. The types of the arguments. Method overriding is beneficial because the overriding method can use the existing code in the super class method and customize it further in the subclass.
Method Overriding & Overloading Method Overloading Method overloading occurs when you have two or more methods that have the same name and return type in a class. The methods have the same name and return type, but each one has a different argument list. Methods are usually overloaded because they serve similar functionality but you wish to give them different inputs.