Public classMain { Public Static voidMain (string[] args) {Chicken C1=NewChicken (); Chicken C2=NULL; C1.eat (); System.out.println (C1.age); C2=C1; C2.eat (); }}classchicken{intcolor; Charsex; intAge ; voideat () {System.out.println ("Chikcen1 eat rice."); }}
Public classMain { Public Static voidMain (string[] args) {person P1=NewPerson (); P1.setname ("Dining"); System.out.println (P1.getname ()); }}/*** closed * 1. Set the property to private * 2. Provide a Get/set method for a property*/classperson{PrivateString name; Private intAge ; Public voidsetName (String name) { This. Name =name; } PublicString GetName () {returnname; }}
Public classMain { Public Static voidMain (string[] args) {Duck P1=NewDuck ("Fishdining"); System.out.println (P1.getname ()); Duck P2=NewDuck ("FishDining2", 20); System.out.println (P2.getname ()+" "+p2.getage ()); }}/*** Construction Method * 1. Default (no parameter) construction method: Public Duck () {} * 2. Constructor with one (multiple) parameter: public Duck (String name) {this.name=name;}*/classduck{PrivateString name; Private intAge ; //default constructor Method PublicDuck () {} PublicDuck (String name,intAge ) { This. Name =name; This. Age =Age ; } PublicDuck (String name) { This. Name =name; System.out.println ("I ' m a duck."); } Public voidsetName (String name) { This. Name =name; } PublicString GetName () {returnname; } Public voidSetage (intAge ) { This. Age =Age ; } Public intGetage () {returnAge ; }}
Public classMain { Public Static voidMain (string[] args) {Woman W1=NewWoman (); W1.aa (); W1.AA ("Keke1"); W1.AA ("Keke1", 21); }}/*** Overloads of methods (methods with the same name but with different parameters and different definitions)*/classwoman{ PublicString name; Public intAge ; Public voidAA () {System.out.println ("Aa1"); } Public voidAA (String name) {System.out.println ("AA2:" +name); } Public voidAA (String name,intAge ) {System.out.println ("Aa2:" +name+ ":" +Age ); }}
ImportJava.util.Random;ImportJava.util.Scanner; Public classMain { Public Static voidMain (string[] args) {NewWoman (). AA ();//generate an anonymous object NewWoman (). AA ("LOVEU1"); }}/*** Anonymous object: Defines an object with no Name, features: can only be used once (directly in the heap to open up memory space, used to become a garbage object, collected by GC)*/classwoman{ PublicString name; Public intAge ; Public voidAA () {System.out.println ("Aa1"); } Public voidAA (String name) {System.out.println ("AA2:" +name); } Public voidAA (String name,intAge ) {System.out.println ("Aa2:" +name+ ":" +Age ); }}
Java notes 2__ class/enclosing/constructor method/method overloads/Anonymous objects